6

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?
kshitij
  • 111
  • 2
  • 2
  • 9
  • You don't need the second split to make charAt[0].toUpper(), a trim is enough. – Pino Apr 18 '13 at 08:59
  • See this earlier [answer](http://stackoverflow.com/questions/1892765/capitalize-first-char-of-each-word-in-a-string-java) – GrahamA Apr 18 '13 at 08:59
  • @Bhaskar- the question is a little different in here i have a string with multiple sentences so first i want to split the sentences then capitalize the word.. my confusion is about how to pass to second split – kshitij Apr 18 '13 at 09:11
  • was any answer helpful? – Vitaly Apr 18 '13 at 09:38
  • @kshitij See my answer below and let me know it works as the way you want or not. – Achintya Jha Apr 18 '13 at 10:52

6 Answers6

13

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());
}
Vitaly
  • 2,760
  • 2
  • 19
  • 26
  • wow! that's clean! and saves the hassle of using different strings thanks! – kshitij Apr 18 '13 at 16:36
  • also I need to extract the first word(except whitespace) after the "." what can i use for that over this? – kshitij Apr 18 '13 at 16:38
  • 1
    @kshitij i'm glad you liked it. "thanks" is a bit better in vote-up and choosing as an answer ;) – Vitaly Apr 18 '13 at 16:39
  • @kshitij `extract the first word` is a separate algorithm not really related to this one. – Vitaly Apr 18 '13 at 16:42
  • 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) == '?'` – Danil Onyanov Sep 06 '16 at 12:18
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.
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
3

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;
}
millimoose
  • 39,073
  • 9
  • 82
  • 134
1

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

WordUtils.capitalizeFully(text, '.')
Ondrej Kvasnovsky
  • 4,592
  • 3
  • 30
  • 40
0

Note that Java Strings are immutable (not modifiable).

Also note that sp[0].charAt(0) will cause an ArrayIndexOutOfBoundsException if there's a space directly after a . (since then the first string will be empty).

I suggest using char[], so something like:

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

Character.isWhitespace(arr[i]) may be preferred to arr[i] != ' '.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
0
char[] strArr = str.toCharArray();
        for (int i = 0; i < strArr.length; i++) {
            if (str.charAt(i) == " ".charAt(0) && i + 1 < strArr.length) {
                strArr[i + 1] = String.valueOf(String.valueOf(strArr[i + 1])).toUpperCase().charAt(0);
            }
        }
        System.out.println(String.valueOf(strArr));
AdZzZ
  • 79
  • 5