Rotation of a String.

package strings;

import java.util.Scanner;

class StringRotation {

    public static void main(String args[]) {
        Scanner in = null;
        try {
            in = new Scanner(System.in);
            String st, g = "";
            int k = 0, c = 0;
            do {
                System.out.print("Enter a String:>");
                st = in.nextLine();
            } while (st.charAt(st.length() - 1) != '.');
            st = st + " ";
            for (int i = 0; i < st.length(); i++) {
                if (st.charAt(i) == ' ') {
                    c++;// counting no. of spaces = no. of words.
                }
            }
            
            //Split into a
            String a[] = new String[c];
            for (int i = 0; i < st.length(); i++) {
                if (st.charAt(i) != ' ') {
                    g += st.charAt(i);
                } else {
                    a[k++] = g;
                    g = "";
                }
            }
            
            // swap within strings.
            for (int i = 0; i < (a.length / 2); i++) {
                String t = a[i];
                a[i] = a[((a.length) - 1) - i];
                a[((a.length) - 1) - i] = t;
            }
            for (int i = 0; i < a.length; i++) {
                g += a[i] + " ";
            }
            System.out.println(g);
        } catch (Exception e) {
        } finally {
        }
    }


}

Comments

Popular posts from this blog

Java important topics list for interviews

Tough Sql practise questions for interviews involving SELECT queries - Part 2

DBMS important topics list for interviews

Program to find number lines and words in a given file

Tough Sql practise questions for interviews involving SELECT queries - Part 1

Producer Consumer Problem with Blocking Queue in Java.

Animation for String search - KMP Algorithm

Interactive Data Structure visualizations/animations for algorithms

Replace Occurances of the given string