/**
* Transforms "StringsLikeThis" into "Strings like this".
*/
private static String separateWords(String interCaps)
{
StringBuilder s = new StringBuilder(interCaps);
for (int i = 1; i < s.length(); i++) {
if (Character.isUpperCase(s.charAt(i))) {
s.setCharAt(i, Character.toLowerCase(s.charAt(i)));
s.insert(ii++, ' ');
}
}
return s.toString();
}
If the sentence contains two consecutive spaces, the function crashes when attempting to take substrings from an empty word.
The one-argument form of String.substring(index)
automatically takes everything to the end.
private static String toPigLatin(String sentence) {
String[] words = sentence.split(" ");
StringBuilder latin = new StringBuilder(sentence.length() + words.length * "ay".length());
for (int i = 0; i < words.length; i++) {
if (i > 0) {
latin.append(' ');
}
String word = words[i];
if (!word.isEmpty()) {
char initial = words[i]word.charAt(0);
char remaining = words[i]word.substring(1);
latin.append(remaining).append(initial).append("ay");
}
}
return latin.toString();
}