【发布时间】:2013-11-11 00:26:32
【问题描述】:
我有一种方法可以将句子中单词的所有首字母转换为大写。
public static String toTitleCase(String s)
{
String result = "";
String[] words = s.split(" ");
for (int i = 0; i < words.length; i++)
{
result += words[i].replace(words[i].charAt(0)+"", Character.toUpperCase(words[i].charAt(0))+"") + " ";
}
return result;
}
问题在于该方法将与第一个字母相同的单词中的其他字母转换为大写。例如,字符串 title 输出为 TiTle
对于输入this is a title,这将成为输出This Is A TiTle
我尝试了很多东西。一个嵌套循环,检查每个单词中的每个字母,如果有重复出现,则忽略第二个。我使用了计数器、布尔值等。没有任何效果,但我一直得到相同的结果。
我能做什么?我只想要大写的第一个字母。
【问题讨论】: