If you don't mind, could you please explain something to me. i understand what this code does for the most part, and how it capitalizes the very first character in the String. What i don't understand is how is capitalizes words after a period, when i read the code it tells me that it "capitalizes" the position(pos) the period is in, not the character either directly after it or a whitespace then a character( "this.example" or "this. example"). Could someone please explain how this code is capitalizing the characters after the period. if need be, please use "today is. a good day" as what would be inputted as 'userInput'.
int pos = 0;
boolean capitalize = true;
StringBuilder sb = new StringBuilder(userInput);
while (pos < sb.length()) {
if (sb.charAt(pos) == '.') {
capitalize = true;
}
else if (capitalize && !Character.isWhitespace(sb.charAt(pos))) {
sb.setCharAt(pos, Character.toUpperCase(sb.charAt(pos)));
capitalize = false;
}
pos++;
}
This code is a crude sort of state machine. Only the if
or the else if
block (or neither) is going to be executed on each iteration of the loop. If the current character is a .
, then the capitalize
flag is set to true
and nothing else happens on that iteration. This flag is telling your code to capitalize the next non-space character it sees.
The loop then takes you to the next character, where it checks to see if the capitalize
flag is true
and the character is not whitespace. If that's the case, the character is capitalized and the flag is reset to false
. If it is a space character, then nothing happens (the capitalize
flag stays true
for the next iteration).