Most of the logic that you have posted works fine. The problem is words like "SENTENCE" because the logic that you are using to check the capitalization is incorrect.
The biggest problem is that you are trying to iterate over the words and check at the same time if that string is or not capitalize.
The easiest way is to separate concerns; try to check beforehand if the word is or not capitalized and act accordingly.
First create a method that just checks if a word is or not capitalized. For example:
public static boolean isUpper(String s, int start) {
for(int i = start; i < s.length(); i++) {
char c = s.charAt(i);
if(c == '.' || c == ' ')
return true;
if (!Character.isUpperCase(c))
return false;
}
return true;
}
This method receives a string (to be checked) and an int
value (i.e., start
) that tells the method from which part of the string should the checking start.
For the getSentenceCaseText
method follow the following strategy. First check if the current word is capitalized:
boolean capitalize = isUpper(text, pos);
if is capitalized the method should skip this word and move to the next one. Otherwise, it capitalizes the first character and lowers the remaining. Apply the same logic to all words in the text.
The code could look like the following:
public static String getSentenceCaseText(String text) {
int pos = 0;
StringBuilder sb = new StringBuilder(text);
// Iterate over the string
while (pos < sb.length()){
// First check if the word is capitalized
boolean capitalize = isUpper(text, pos);
char c = sb.charAt(pos);
// Make the first letter capitalized for the cases that it was not
sb.setCharAt(pos, Character.toUpperCase(c));
pos++;
// Let us iterate over the word
// If it is not capitalized let us lower its characters
// otherwise just ignore and skip the characters
for (;pos < sb.length() && text.charAt(pos) != '.' && text.charAt(pos) != ' '; pos++)
if(!capitalize)
sb.setCharAt(pos, Character.toLowerCase(sb.charAt(pos)));
// Finally we need to skip all the spaces
for(; pos < sb.length() && text.charAt(pos) == ' '; pos++ );
}
return sb.toString();
}
Use this strategy and this code as guide, build upon it and implement your own method.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…