Capitalize first word of a sentence in a string with multiple sentences

13,070

Solution 1

Use StringBuilder, 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());
}

Solution 2

No need to mess with splitting and splicing, you can work in-place on a character array:

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;
}

Solution 3

Try this to capitalize first letter of the sentence. I just did little changes in your code.

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);
}

Output:

This is.A good boy.

Solution 4

If you can use WordUtils from Apache commons-lang3, do this:

WordUtils.capitalizeFully(text, '.')
Share:
13,070
kshitij
Author by

kshitij

Updated on June 18, 2022

Comments

  • kshitij
    kshitij almost 2 years

    eg:

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

    should come out as

    "This is a.Line is.Over"

    I thought of using string tokenizer 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 string tokenizer as input for another?

    also i can using the split method to generate array something i 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?
    
  • smttsp
    smttsp about 11 years
    You need to add the first character to be upper case
  • Bernhard Barker
    Bernhard Barker about 11 years
    @smttsp The first character of the string? It will be upper-case since capitalize starts as true.
  • kshitij
    kshitij about 11 years
    wow! that's clean! and saves the hassle of using different strings thanks!
  • kshitij
    kshitij about 11 years
    also I need to extract the first word(except whitespace) after the "." what can i use for that over this?
  • Vitaly
    Vitaly about 11 years
    @kshitij i'm glad you liked it. "thanks" is a bit better in vote-up and choosing as an answer ;)
  • Vitaly
    Vitaly about 11 years
    @kshitij extract the first word is a separate algorithm not really related to this one.
  • kshitij
    kshitij about 11 years
    thanks!it works just fine but I'm worried that multiple conversions might slow it down on larger data.
  • Achintya Jha
    Achintya Jha about 11 years
    @kshitij I think this is best solution here if you use StringBuilder instead of String for output variable.
  • Danil Onyanov
    Danil Onyanov over 7 years
    To future readers. If you need to define all types of sentences, replace if case to sb.charAt(pos) == '.' || sb.charAt(pos) == '!' || sb.charAt(pos) == '?'