Search code examples
javastringalgorithmreverse

How can I reverse a string word by word without using arrays, split() or StringBuilder


I'm trying to reverse a string word by word without using arrays, split() or StringBuilder. This is my code so far. It works, but my output is not how I want it. See my image for output. I want my program to output each word on a new line. Also notice how the letter "n" is missing from curtain and there is no space between the last two words. How can I fix this?

public static void main(String[] args) {

    String sentence = new String("pay no attention to that man behind the curtain");
    String reversed = "";

    int endIndex = sentence.length()-1;
    for(int i = endIndex; i >= 0; i--) {
        if(sentence.charAt(i) == ' ') {
            reversed += sentence.substring(i, endIndex);
            endIndex = i;
        }
    }
    reversed += sentence.substring(0, endIndex);
    System.out.println(reversed);
}

enter image description here


Solution

  • First of all, there is a better way to reverse the words. But lets look at your program.

    I want my program to output each word on a new line.

    If you want to print each word in a new line, you could either add each word to a list of words and print each word in a new line or you could just add "\n" at the end of each word.

    Also notice how the letter "n" is missing from curtain and there is no space between the last two words.

    This is because the endIndex starts at sentence.length()-1 and substring in Java works by extracting from startIndex to endIndex - 1 i.e. endIndex is exclusive and startIndex is inclusive. You can fix it by declaring endIndex = sentence.length() and iterate from i = sentence.length()-1 to 0.

    With that the code would be:

    public static void main(String[] args) {
    
        String sentence = new String("pay no attention to that man behind the curtain");
        String reversed = "";
    
        int endIndex = sentence.length();
        for(int i = sentence.length()-1; i >= 0; i--) {
            if(sentence.charAt(i) == ' ') {
                reversed += sentence.substring(i+1, endIndex) + "\n";
                endIndex = i;
            }
        }
        reversed += sentence.substring(0, endIndex);
        System.out.println(reversed);
      }
    

    The better way is :

    a) Convert your string to character array

    b) Then reverse the whole character array which would become :

    niatruc eht dniheb nam taht ot noitnetta on yap
    

    c) Then reverse the letters between each space in-place.

    d) You will get back the new character array that represents:

    curtain the behind man that to attention no pay
    

    and you can construct a string from the new character array.