如何将字符串中每个单词的第一个和最后一个字母大写
我是这样做的-
String cap = "";
for (int i = 0; i < sent.length() - 1; i++)
{
if (sent.charAt(i + 1) == ' ')
{
cap += Character.toUpperCase(sent.charAt(i)) + " " + Character.toUpperCase(sent.charAt(i + 2));
i += 2;
}
else
cap += sent.charAt(i);
}
cap += Character.toUpperCase(sent.charAt(sent.length() - 1));
System.out.print (cap);
当第一个单词超过单个字符时,它不起作用
我是初学者,请使用简单的函数
最佳答案
使用 apache commons lang
library它变得非常容易做到:
String testString = "this string is needed to be 1st and 2nd letter-uppercased for each word";
testString = WordUtils.capitalize(testString);
testString = StringUtils.reverse(testString);
testString = WordUtils.capitalize(testString);
testString = StringUtils.reverse(testString);
System.out.println(testString);
ThiS StrinG IS NeedeD TO BE 1sT AnD 2nD Letter-uppercaseD FoR EacH WorD
关于java - 如何在java中将字符串中每个单词的第一个和最后一个字母大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42302018/