0

So i've got a for loop that's reversing every other word in a string. I can't determine which condition is causing this. I've spent a good amount of time staring at this and the API, to no avail. Anyone have any idea why it's not working?

String newMessage;
    StringBuilder stringBuilder = new StringBuilder();
    newMessage = messageToEncrypt.replaceAll("[^0-9a-zA-z\\s]",""); //check for a non-word character
    String[] words = newMessage.split("\\s"); // Array to split the words into each index
    for (int i = 0; i < words.length; i++) 
    {
        stringBuilder.append(words[(words.length-1)-i]);
        stringBuilder.reverse();
        //stringBuilder.append(words[words.length-1]);
        stringBuilder.append(" ");

    }
    newMessage = stringBuilder.toString();
    return newMessage;
2
Contributors
1
Reply
18
Views
2 Years
Discussion Span
Last Post by JamesCherrill
1

Every time you append a word you reverse the entire string, so the last word is reversed once, the previous word is reversed twice, the word before that is reversed 3 times, ... , and the first word is reversed (words.length) times. Of couse an even number of reversals is the same as not reversing.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.