2

I need some help parsing a string that is input to one that is later cleaned and output.

e.g.

String str = " tHis  strIng is  rEalLy mEssy  "

and what I need to do is have it parsed from that to look like this:

"ThisStringIsReallyMessy"

so I basically need to clean it up then set only the first letter of every word to capitals, without having it break in case someone uses numbers.

Fate Averie
  • 359
  • 4
  • 7
  • 17

4 Answers4

5

Apache Commons to the rescue (again). As always, it's worth checking out the Commons libraries not just for this particular issue, but for a lot of functionality.

You can use Apache Commons WordUtils.capitalize() to capitalise each word within the string. Then a replaceAll(" ", "") will bin your whitespace.

String result = WordUtils.capitalize(str).replaceAll(" ", "");

Note (other) Brian's comments below re. the choices behind replace() vs replaceAll().

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • Note that `replaceAll` takes a regex. Use `replace` for non-regex replacement since it's faster and does the same thing. Also on that note, `replaceAll("\\s+", "")` will also replace tabs and other whitespace besides the space character. – Brian Sep 25 '12 at 17:03
  • @Brian - I've amended my answer to refer to your comment above. Thx – Brian Agnew Sep 25 '12 at 17:04
4
   String str = " tHis  strIng is  rEalLy mEssy  ";
   str =str.replace(" ", "");
   System.out.println(str);

output:

tHisstrIngisrEalLymEssy

For capitalizing first letter in each word there is no in-built function available, this thread has possible solutions.

Community
  • 1
  • 1
kosa
  • 65,990
  • 13
  • 130
  • 167
4
String[] tokens = " tHis  strIng is  rEalLy mEssy  ".split(" ");
StringBuilder result = new StringBuilder();
for(String token : tokens) {
    if(!token.isEmpty()) {
        result.append(token.substring(0, 1).toUpperCase()).append(token.substring(1).toLowerCase());
     }
}
System.out.println(result.toString()); // ThisStringIsReallyMessy
kapex
  • 28,903
  • 6
  • 107
  • 121
0

Do you mean this?

str = str.replaceAll(" ", "");
Sebastian vom Meer
  • 5,005
  • 2
  • 28
  • 36