简体   繁体   中英

Java capitalizing first letter of every word in string array

Excuse the brevity, currently on mobile.

I have a string array of values ABC, DEF, GHI that I would like to change to capitalized form: Abc, Def, Ghi

My code looks something like this:

import org.apache.commons.lang3.text.WordUtils;

....

final String[] split = stringToConvert.split(", ");

final StringBuilder sb = new StringBuilder();

for ( String s : split) {
   //s = WordUtils.capitalizeFully(s.toLowerCase());

  if (sb.length() > 0) {
    sb.append(", ");
  }
  sb.append(WordUtils.capitalizeFully(s.toLowerCase()));
}

return sb.toString();

The first value is always abc, but the second and following ones are correct, eg Def, Ghi. I don't know why the first value stays lowercase.

Any help would be appreciated!

Check your code again.

StringBuilder buf = new StringBuilder();

for (String str : new String[]{"ABC", "DEF", "GHI"})
    buf.append(WordUtils.capitalizeFully(str.toLowerCase()));

System.out.println(buf);

Prints AbcDefGhi , as expected.

It could be simplier, if you use Stream :

String res = Stream.of("ABC", "DEF", "GHI")
        .map(WordUtils::capitalizeFully)
        .collect(Collectors.joining(", "));    // if you want to split words with comma

Your code should work.

May I however suggest using a stream instead?

String concatenatedString = Arrays.stream(array)
    .map(WordUtils::capitalizeFully)
    .collect(Collectors.joining());

Which, with appropriate static imports fits well on one line without losing readability:

String concatenatedString = stream(array).map(WordUtils::capitalizeFully).collect(joining());

Note that joining() uses a StringBuilder iternally, so you don't need to worry about performance here. Also, joining() allows you to choose which string you want to delimit the content of the stream with, in this case I chose an empty string, which would result in AbcDefGhi .

This should do :

String[] stringToSplit = {"ABC", "DEF", "GHI"};
StringBuilder sb = new StringBuilder();

for(String s: stringToSplit) {
   sb.append(s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase());
}

Update: I'm tired...

The first character was actually a [ from the array instead of "a", thus the a was never capitalized

Thanks all, and sorry for wasting your time

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM