Basically, you just need to iterate over all the characters and replace them if one of the following conditions is true:
- this is the first character
- this is the last character
- the previous character was a space (or what you want, for example, punctuation - see below)
- the next character is a space (or whatever you want, such as punctuation - see below)
If you use StringBuilder for performance and memory reasons (don't create a String at every iteration that will be executed += ), it might look like this:
StringBuilder sb = new StringBuilder( "some words in a list even with longer whitespace in between" ); for( int i = 0; i < sb.length(); i++ ) { if( i == 0 || //rule 1 i == (sb.length() - 1 ) || //rule 2 Character.isWhitespace( sb.charAt( i - 1 ) ) || //rule 3 Character.isWhitespace( sb.charAt( i + 1 ) ) ) { //rule 4 sb.setCharAt( i, Character.toUpperCase( sb.charAt( i ) ) ); } }
Result: SomE WordS IN A LisT EveN WitH LongeR WhitespacE IN BetweeN
If you want to check other rules (for example, punctuation, etc.), you can create a method that you call for the previous and next character, and which checks the required properties.
source share