Search code examples
javastringstringbuilderstringbuffer

How to print String buffer lines from last to first order


I have requirement to print String buffer lines as last to first order.

Example :toString of Stringbuffer method is printing below output:

this
is
some
text

Desired output:

text
some
is
this

Solution

  • What you could do is to create an array, iterate over it.

    String s = new String("this\nis\nsome\ntext");
    String []tokens = s.split("\n");
    for(int i = tokens.length - 1; i >= 0; --i)
       System.out.println(tokens[i]);
    

     StringBuffer s = new StringBuffer("this\nis\nsome\ntext");
        String []tokens = s.toString().split("\n");
        for(int i = tokens.length - 1; i >= 0; --i)
           System.out.println(tokens[i]);
    

    A better memory less approach would be.

    StringBuffer s = new StringBuffer("this\nis\nsome\ntext");
            String word = ""; 
            for(int i = s.length() - 1; i >= 0; --i)
            {
                if(s.charAt(i) != '\n')
                {
                    word = s.charAt(i) + word;
                }
                else{
                    System.out.println(word);
                    word = "";
                }
            }
            if(!word.equals(""))
                System.out.println(word);