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
Post a Comment