Java – capitalize the first word in a string with multiple sentences

For example:

String s = "this is a.line. Over"

Should come out

"This is a.line is. Over"

I thought about using string markers twice

-first split using"."

 -second split using " " to get the first word

 -then change charAt[0].toUpper

Now I'm not sure how to use the output of the string marker as the input of another?

I can also use the split method to generate the array I've tried

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?

Solution

With StringBuilder, there is no need to split and create other strings, and so on, see the code

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());
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>