Thursday, April 30, 2009

Reversing String in Java

This post is about String manipulation. I have provided solutions to some problems/teasers such as how to reverse a String without using the reverse method, how to reverse individual words in a sentence without reversing the sentence and how to reverse a sentence without reversing the words in it. There are many ways to do it and I have presented one or two. It was pure fun doing this exercise.

And remember unless there is a real need to rewrite core functionality don't do it.

import java.util.Stack;
import java.util.StringTokenizer;

public class MyStringTests {

/**
* Reverses word and if a sentence is provided, reverses
* the sentence and all words in the sentence.
* @param s is the input string
* @return the modified string
* eg:
* HELLOO WORLD
* becomes
* DLROW OOLLEH
* eg:
* HELOO becomes
* OOLEH
*/
public static String reverseWord(String s) {
if (s == null || s.length() <= 1) return s;
char[] a = s.toCharArray();
int len = a.length - 1;
char temp;
for(int i = 0, j = len; i <= j; i++,j--) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
return new String(a);
}

/**
* Ideal way to reverse a string in Java is to use
* the reverse method of StringBuffer. Unless there
* is a real need to rewrite core functionality don't
* do it.
* @param s is the input string
* @return the modified string
* eg:
* HELLOO WORLD
* becomes
* DLROW OOLLEH
* eg:
* HELOO becomes
* OOLEH
*/
public static String reverseWordUsingReverse(String s) {
if (s == null || s.length() <= 1) return s;
StringBuffer sb = new StringBuffer(s);
return sb.reverse().toString();
}

/**
* Reverses a sentence without reversing individual
* words in it
* @param s is the input string
* @return the modified string
* eg:
* HELLOO WORLD
* becomes
* WORLD HELLO
*/
public static String reverseSentence(String s) {
if (s == null || s.length() <= 1) return s;
StringTokenizer strtok = new StringTokenizer(s);
if (strtok.countTokens() <= 1) return s;
Stack<String> stack = new Stack<String>();
while (strtok.hasMoreTokens()) {
stack.push((String)strtok.nextToken());
}
StringBuffer sb = new StringBuffer();
while (!stack.isEmpty()) {
sb.append(stack.pop());
sb.append(" ");
}
return sb.toString();
}

/**
* Reverses a sentence without reversing individual
* words in it
* @param s is the input string
* @return the modified string
* eg:
* HELLOO WORLD
* becomes
* WORLD HELLO
*/
public static String reverseSentenceUsingSplit(String s) {
if (s == null || s.length() <= 1) return s;
String[] sa = s.split(" ");
if (sa.length <= 1) return s;
StringBuffer newString = new StringBuffer();
for(int i = 0, j = (sa.length - 1); i <= j; i++,j--) {
newString.append(sa[j]).append(" ").append(sa[i]);
}
return newString.toString();
}

/**
* Reverses each word in a sentence but not the
* sentence
* @param s is the input string
* @return the modified string
* eg:
* HELLOO WORLD
* becomes
* OOLLEH DLROW
*/
public static String reverseWordInSentence(String s) {
if (s == null || s.length() <= 1) return s;
StringTokenizer strtok = new StringTokenizer(s);
StringBuffer sb = new StringBuffer();
while (strtok.hasMoreTokens()) {
sb.append(reverseWord(
(String)strtok.nextToken()));
sb.append(" ");
}
return sb.toString();
}


public static void main(String[] args) {
//Test
String s = "HELLOO WORLD";
print(s);
print(reverseWord(s));
print(reverseWordUsingReverse(s));
print(reverseSentence(s));
print(reverseSentenceUsingSplit(s));
print(reverseWordInSentence(s));
}

//Helper print method
public static <T> void print(T s) {
System.out.println(s);
}


}



The output is:
HELLOO WORLD
DLROW OOLLEH
DLROW OOLLEH
WORLD HELLOO
WORLD HELLOO
OOLLEH DLROW

No comments:

Post a Comment