Recently, in an interview, i was asked to reverse a sentence, i.e. given a String “THIS IS AN INTERVIEW” , reverse it to “INTERVIEW AN IS THIS” without using any advanced APIs of Java.
I had tried to solve the problem with the java.util.regex.Pattern class after realizing that usage of StringTokenizer is discouraged in the Java Docs. However,the solution was not accepted as it used Pattern class. So, i was determined to solve the problem myself and have come up with the below solution. Please provide your valuable feedback. The soultion here uses basic classes like String, StringBuilder and char. The solution here can be enhanced for a character-sequence. Currently, it works only for a single character.
import java.util.regex.Pattern;
public class TestStringSplitAndReversal {
public static void main(String args[]) {
String testString = "THIS IS A TEST";
char regex = ' ';
String[] reversedString = TestStringSplitAndReversal.split(regex, testString);
int size = reversedString.length;
//For String reversal
for (int i = size - 1; i >= 0; i--) {
if (reversedString[i] != null)
System.out.println("Element:::" + reversedString[i]);
}
}
// Regular Splitting using Java's API
public static String[] split(String regex, String str) {
return Pattern.compile(regex).split(str);
}
// Splitting without using any advanced APIs of Java
public static String[] split(char regex, String str) {
char[] actual = str.toCharArray();
// char[] temp=new char[str.length()];
StringBuilder tempStr = new StringBuilder();
int j = 0, k = 0;
String[] result = new String[str.length()];
int resultSize = 1;
for (int i = 0; i < actual.length; i++) {
// temp[j++]=actual[i];
tempStr = tempStr.append(actual[i]);
if (regex == actual[i]) {
result[k++] = new String(tempStr);
// j=0;
resultSize++;
// temp=new char[str.length()];
tempStr = new StringBuilder();
}
}
// result[k++]=new String(temp);
result[k++] = new String(tempStr);
return resizeArray(result, resultSize);
}
//This resizing is required as once an Array is initialized to a size,
//it cannot be shrinked.Hence, we need to create a new Array.
public static String[] resizeArray(String[] original, int resultCount) {
String[] result = new String[resultCount];
for (int i = 0; i < original.length; i++) {
if (original[i] != null) {
result[i] = original[i];
}
}
return result;
}
}