是否有一种简单的方法可以将java字符串转换为标题大小写(包括diacritics ),而不需要第三方库。
我发现了这个老问题,但我认为Java从那以后得到了许多改进。
Is there a method for String conversion to Title Case?
示例:
zola
预期结果:
O'Connor
发布于 2021-05-08 12:05:40
我在regex中使用此方法:
public static void main(String[] args) {
System.out.println(titleCase("JEAN-CLAUDE DUSSE"));
System.out.println(titleCase("sinéad o'connor"));
System.out.println(titleCase("émile zola"));
System.out.println(titleCase("O'mALLey"));
}
public static String titleCase(String text) {
if (text == null)
return null;
Pattern pattern = Pattern.compile("\\b([a-zÀ-ÖØ-öø-ÿ])([\\w]*)");
Matcher matcher = pattern.matcher(text.toLowerCase());
StringBuilder buffer = new StringBuilder();
while (matcher.find())
matcher.appendReplacement(buffer, matcher.group(1).toUpperCase() + matcher.group(2));
return matcher.appendTail(buffer).toString();
}
我已经测试过你的弦了。
以下是要输出的结果:
Jean-Claude Dusse
Sinéad O'Connor
Émile Zola
O'Malley
发布于 2021-05-08 12:22:09
实现这个目标的两种方法-
使用Apache的
public static String convertToTileCase(String text) {
return WordUtils.capitalizeFully(text);
}
自定义函数
private final static String WORD_SEPARATOR = " ";
public static String changeToTitleCaseCustom(String text) {
if (text == null || text.isEmpty()) {
return text;
}
return Arrays.stream(text.split(WORD_SEPARATOR))
.map(word -> word.isEmpty()
? word
: Character.toTitleCase(word.charAt(0)) + word.substring(1).toLowerCase()
)
.collect(Collectors.joining(WORD_SEPARATOR));
}
调用上面的自定义函数-
System.out.println(
changeToTitleCaseCustom("JEAN-CLAUDE DUSSE") + "\n" +
changeToTitleCaseCustom("sinéad o'connor") + "\n" +
changeToTitleCaseCustom("émile zola") + "\n" +
changeToTitleCaseCustom("O'mALLey") + "\n");
产出-
Jean-claude Dusse
Sinéad O'connor
Émile Zola
O'malley
发布于 2022-09-29 14:49:58
非常喜欢正则表达式,但是如果有人想要一个不同的解决方案,这是我的解决方案。据我所知,唯一的拆分字符应该是-
和'
。
public static String toTitleCase(String content) {
if (content == null || content.isEmpty()) {
return content;
}
HashSet<Character> splitSet = new HashSet<Character>(Arrays.asList(new Character[]{' ', '-', '\''}));
char[] titleCased = new char[content.length()];
for (int i = 0; i < content.length(); i++) {
boolean applyTitleCase = i == 0 || splitSet.contains(content.charAt(i - 1));
char targetChar = content.charAt(i);
titleCased[i] = applyTitleCase ? Character.toTitleCase(targetChar) : Character.toLowerCase(targetChar);
}
return new String(titleCased);
}
https://stackoverflow.com/questions/67447311
复制相似问题