This operation is called capitalize , regardless of language. Not knowing Java at all, I googled Java capitalize and the first (!) Link gave:
WordUtils.capitalize(string)
https://stackoverflow.com/questions/1892765/capitalize-first-char-of-each-word-in-a-string-java
Actually, in one line without third-party libraries:
str = str.replaceAll("((^|\\s+)(\\w))", "$2\\u\\$3");
Honestly, I donβt know if \u works in Java, but you can:
str = str.replaceAll("((^|\\s+)(\\w))", "$2" + "$3".toUpperCase());
A regular looks for either the first letter in a string, or a letter that stands behind an arbitrary number of spaces and brings it to upper case, keeping what was before it (the same number of spaces, or nothing). I donβt have Java, perl testing, it works there.
P.S. outer parentheses are probably not needed.
Unfortunately, the proposed method without WordUtils will not work in Java for several reasons. The problem is interesting, so I will give its solution in a couple of other languages.
1) perl. The coolest of all. One line. There is no point even writing a function. perl, IMHO, cooler than all languages ββworks with strings:
my $s = "simple string - example, Π° ΡΠ΅ΠΏΠ΅ΡΡ Π ΡΡΡΠΊΠΈΠΉ ΡΠ΅ΠΊΡΡ"; $s =~ s/(\b\w)/\u$1/g; print "$s\n";
2) python. (The solution in Java will be similar, in 2.x Python it works only with English letters, alas)
def capitalize(s): for g in re.finditer(r"^|\s+\w", s): s = s.replace(g.group(0), g.group(0).upper(), 1) return s if __name__ == "__main__": s = capitalize("my text solo\t\t\t\tstring\nmmm") print s