You are appending to the same string that you are iterating through. Instead, just make your sentence
an empty StringBuilder
. Then you can append to that while iterating through input
. For example:
StringBuilder sentence = new StringBuilder();
//add spaces between the words
for(int i=0; i < input.length(); i++)
{
char letter = input.charAt(i);
if(i != 0 && Character.isUpperCase(letter))
{
sentence.append(' ');
sentence.append(Character.toLowerCase(letter));
}
else
{
sentence.append(letter);
}
}
(Note that I've changed the variable name from index
to letter
, which is a lot less confusing.)