My app receives a large amount of paragraph length text. Some of it is all in upper case, some all lower and some a mix. I would like to convert it to sentence case i.e. all sentences should start with an uppercase letter. What would be the most efficient way to perform the conversion? - I could not find any sample code or a library to do this.
Asked
Active
Viewed 1,733 times
1 Answers
3
The code referenced in the links above did not quite work, so I extended it as follows to turn text like:
"this SENTENce is not neat. neither IS this sentence."
into
"This sentence is not neat. Neither is this sentence."
public static String sentenceCaseForText(String text) {
if (text == null) return "";
int pos = 0;
boolean capitalize = true;
StringBuilder sb = new StringBuilder(text);
while (pos < sb.length()) {
if (capitalize && !Character.isWhitespace(sb.charAt(pos))) {
sb.setCharAt(pos, Character.toUpperCase(sb.charAt(pos)));
}
else if (!capitalize && !Character.isWhitespace(sb.charAt(pos))) {
sb.setCharAt(pos, Character.toLowerCase(sb.charAt(pos)));
}
if (sb.charAt(pos) == '.' || (capitalize && Character.isWhitespace(sb.charAt(pos)))) {
capitalize = true;
}
else {
capitalize = false;
}
pos++;
}
return sb.toString();
}

RunLoop
- 20,288
- 21
- 96
- 151