将句子中的第一个单词用多个句子大写

例如:

String s =“这是a.line是.over”

应该出来

“这是a.Line is.Over”

我想过两次使用字符串标记器

-first split using"." -second split using " " to get the first word -then change charAt[0].toUpper 

现在我不确定如何使用字符串标记符的输出作为另一个的输入?

我也可以使用split方法生成我尝试过的数组

  String a="this is.a good boy"; String [] dot=a.split("\\."); while(i<dot.length) { String [] sp=dot[i].split(" "); sp[0].charAt(0).toUpperCase();// what to do with this part? 

使用StringBuilder,无需拆分和创建其他字符串,依此类推,请参阅代码

 public static void main(String... args) { String text = "this is a.line is. over"; int pos = 0; boolean capitalize = true; StringBuilder sb = new StringBuilder(text); while (pos < sb.length()) { if (sb.charAt(pos) == '.') { capitalize = true; } else if (capitalize && !Character.isWhitespace(sb.charAt(pos))) { sb.setCharAt(pos, Character.toUpperCase(sb.charAt(pos))); capitalize = false; } pos++; } System.out.println(sb.toString()); } 

试试这个来大写句子的第一个字母。 我刚刚对你的代码做了一些改动。

 public static void main(String[] args) { String a = "this is.a good boy"; String[] dot = a.split("\\."); int i = 0; String output = ""; while (i < dot.length) { dot[i] = String.valueOf(dot[i].charAt(0)).toUpperCase() + dot[i].substring(1); output = output + dot[i] + "."; i++; } System.out.println(output); } 

输出:

 This is.A good boy. 

无需混乱拆分和拼接,您可以在字符数组上就地工作:

 String s = "this is a.line is .over "; char[] cs = s.toCharArray(); // make sure to capitalise the first letter in the string capitaliseNextLetter(cs, 0); for (int i = 0; i < cs.length; i++) { // look for a period if (cs[i] == '.') { // capitalise the first letter after the period i = capitaliseNextLetter(cs, i); // we're assigning to i to skip the characters that // `capitaliseNextLetter()` already looked at. } } System.out.println(new String(cs)); // This will capitalise the first letter in the array `cs` found after // the index `i` private static int capitaliseNextLetter(char[] cs, int i) { for (; i < cs.length; i++) { // This will skip any non-letter after the space. Adjust the test // as desired if (Character.isAlphabetic(cs[i])) { cs[i] = Character.toUpperCase(cs[i]); return i; } } return cs.length; } 

如果您可以使用Apache commons-lang3中的WordUtils ,请执行以下操作:

 WordUtils.capitalizeFully(text, '.') 

请注意,Java字符串是不可变的(不可修改)。

另请注意,如果在a之后有空格, sp[0].charAt(0)将导致ArrayIndexOutOfBoundsException . (从那以后第一个字符串将为空)。

我建议使用char[] ,所以类似于:

  String a = "this is.a good boy"; char arr[] = a.toCharArray(); boolean capitalize = true; for (int i = 0; i < arr.length; i++) if (arr[i] == '.') capitalize = true; else if (arr[i] != ' ' && capitalize) { arr[i] = Character.toUpperCase(arr[i]); capitalize = false; } a = new String(arr); 

对于arr[i] != ' ' Character.isWhitespace(arr[i])可能更arr[i] != ' '