Tuesday, May 5, 2020

Reversing a String by Word or by Character

You wish to reverse a string, a character, or a word at a time. You can reverse a string by character easily, using a StringBuilder. One natural way is to use a StringTokenizer and a stack. Stack is a class that implements an easy-to-use last-in, first-out (LIFO)
import java.util.Stack;
import java.util.StringTokenizer;

public class reverse {

    public static void main(String[] argv) {
        //Using StringBuilder reverse() 
        String sh = "Hello World 2020";
        System.out.println(sh + " -> " + new StringBuilder(sh).reverse());
        //Hello World 2020 -> 0202 dlroW olleH

        //Using Stack & StringTokenizer pushing and poping whole word
        String s = "Hello World 2020";

        Stack<String> myStack = new Stack<>();
        StringTokenizer st = new StringTokenizer(s);
        while (st.hasMoreTokens()) {
            myStack.push(st.nextToken());
        }

        // Print the stack backwards
        System.out.print('"' + s + '"' + " backwards by word is:\n\t\"");
        while (!myStack.empty()) {
            System.out.print(myStack.pop());
            System.out.print(' ');
        }
        System.out.println('"');
        //"Hello World 2020" backwards by word is:
 //"2020 World Hello "
    }
}

No comments:

Post a Comment