1

I'm getting user input that I need to format. I need to remove all leading/trailing spaces and I need to capitalize the first letter of each word.

Here is what I'm trying, however... if you input something with 2 spaces between words, it crashes. How might I solve this?

String formattedInput = "";
String inputLineArray[] = inputLine.getText().toString().trim().split("\\s");
for (int d=0; d<inputLineArray.length; d++) {
    formattedInput = formattedInput.trim() + " " +   
            inputLineArray[d].trim().substring(0,1).toUpperCase() +
            inputLineArray[d].trim().substring(1).toLowerCase();
}
John Giotta
  • 16,432
  • 7
  • 52
  • 82
Roger
  • 4,249
  • 10
  • 42
  • 60
  • Possible solution http://stackoverflow.com/questions/1892765/capitalize-first-char-of-each-word-in-a-string-java – John Giotta Apr 12 '11 at 19:59
  • You should note that your current code is not meeting your stated requirements. Your requirement is to "capitalize the first letter" not "make all the other ones lower case". I'm curious why you're making them all lower case. If I pass in "rOgEr" I would expect "ROgEr" not "Roger". – corsiKa Apr 12 '11 at 20:13

2 Answers2

1

Your code is blowing up on multiple spaces because when you split you're getting a member in your array that is an empty string "hello there" when split becomes array[0] = "hello", array[1] = "", array[2] = "there".

So when you do substring(0,1) you should get an IndexOutOfBoundsException.

Try changing your split("\\s") to split("\\s+") this way your multiple spaces get picked up in the regex and thrown out.

Edit:

This also will let you get rid of the .trim() inside your loop since all of the spaces will be taken care of by the split.

Shaded
  • 17,276
  • 8
  • 37
  • 62
0

tokenize the string and split by space " " and then take each iteration and capitalize it and then put it back together again

read all about string tokenization here

Naftali
  • 144,921
  • 39
  • 244
  • 303
  • -1 `String.split(String regex)` was introduced for the sole purpose of obsoleting `StringTokenizer`, which is bulky and awkward in comparison. – corsiKa Apr 12 '11 at 20:04
  • @glowcoder, i have not done java in a while, that is how i learned to split a string. with a tokenizer – Naftali Apr 12 '11 at 20:05