[英]Is there a simple way to convert java string to title case including diacritics, without third party library
Is there a simple way to convert java string to title case including diacritics, without third party library.有没有一种简单的方法可以将 java 字符串转换为包括变音符号在内的标题大小写,无需第三方库。
I have found this old question but I think that Java has got many improvement since.我发现了这个老问题,但我认为 Java 从那以后有了很多改进。
Is there a method for String conversion to Title Case? 有没有将字符串转换为标题大小写的方法?
Examples:例子:
Expected results:预期成绩:
I use this method with 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();
}
I have tested with your strings.我用你的琴弦测试过。
Here is the results to output:这是 output 的结果:
Jean-Claude Dusse
Sinéad O'Connor
Émile Zola
O'Malley
Two ways to achieve this -实现这一目标的两种方法 -
Using Apache Commons Library使用 Apache 公共库
public static String convertToTileCase(String text) {
return WordUtils.capitalizeFully(text);
}
Custom function定制 function
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));
}
Calling above custom function -上面调用自定义 function -
System.out.println(
changeToTitleCaseCustom("JEAN-CLAUDE DUSSE") + "\n" +
changeToTitleCaseCustom("sinéad o'connor") + "\n" +
changeToTitleCaseCustom("émile zola") + "\n" +
changeToTitleCaseCustom("O'mALLey") + "\n");
Output - Output -
Jean-claude Dusse
Sinéad O'connor
Émile Zola
O'malley
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.