Im trying to reverse characters in a sentence without using the split function. Im really close but I am missing the final letter. Can some one please point me in the right direction? Right now it prints “This is a new sentence” as “sihT si a wen cnetnes” Also I included if(start == 0) because the program would skip the initial space character, but I don’t understand why?
static String reverseLetters(String sentence)
StringBuilder reversed = new StringBuilder("");
int counter = 0;
int start = 0;
String word;
for(int i = 0; i <= sentence.length()-1 ; i++ )
{
if(sentence.charAt(i)== ' '|| i == sentence.length()-1 )
{
StringBuilder sb = new StringBuilder("");
sb.append(sentence.substring(start,i));
if(start == 0)
{
start = i;
word = sb.toString();
reversed.append(reverseChar(word));
reversed.append(' ');
}
else
{
start = i;
word = sb.toString();
reversed.append(reverseChar(word));
}
}
return reversed.toString();
}
static String reverseChar (String word)
{
StringBuilder b = new StringBuilder("");
for(int idx = word.length()-1; idx >= 0; idx -- )
{
b.append(word.charAt(idx));
}
return b.toString();
}
I think the error lies in the index, the
forshould beThen
ifshould be:if (sentence.charAt(i==0?0:i-1)== ' '|| i == sentence.length() )For me the error will be that the
substring(start,i)for the last oneishould be sentence.length instead of sentence.length-1, so this would solve it.Substring is open in the last index, so if you put
substring(1, 10)will be substring from 1 to 9. That might be the problem with last word.The thing with the first space is also the problem with substring, let’s say you’re reading “this is…” the first time it will do a subtring with
start=0andi = 4so you expect “this ” but it really is “this”. The next reading, withstart=4andi=7will be ” is”.So with the change of the index you should be able to remove the if/else with
start==0too.