I think the error lies in the index, for should be
for(int i = 0; i <= sentence.length() ; i++ )
Then if should be:
if (sentence.charAt(i==0?0:i-1)== ' '|| i == sentence.length() )
For me, the error will be that substring(start,i) for the last i should be description.length instead of expression.length-1, so this will solve it.
Substring is open at the last index, so if you put substring(1, 10) , there will be a substring from 1 to 9. This may be a problem with the last word.
The thing with the first space is also a substring problem, let's say you read “this ...” the first time that it performs the substitution with start=0 and i = 4 so that you expect “this” but it really is “this”. The next read with start=4 and i=7 will be "is".
So, with changing the index, you can also remove if / else with start==0 .
source share