Reversing words in a string is a popular coding interview question. Here what is meant by reversing words in a string is something like this.
Input string: “My name is rajind and i am a believer”
Output string: “believer a am i and rajind is name My”
Doing this in-place without use additional space to store the string is the trick. Following is the java code to do that.
/**
*
* @author Rajind
*/
public class ReverseWordsString {
public static char[] stringReverse(char[] arr, int start, int end){
while(start < end){
arr[start] = (char) (arr[start]^arr[end]);
arr[end] = (char) (arr[start]^arr[end]);
arr[start] = (char) (arr[start]^arr[end]);
start++;
end--;
}
return arr;
}
public static void main(String Args[]){
/*char a = 'A';
char b = 'B';
a = (char) (a^b);
b = (char) (a^b);
a = (char) (a^b);
System.out.println(a + " "+ b);
*/
char[] str = "My name is rajind and i am a believer".toCharArray();
str = stringReverse(str, 0, str.length -1);
int start = 0;
for(int i=0; i < str.length; i++){
if(str[i] == ' '){
str = stringReverse(str, start, i-1);
start = i + 1;
}
}
str = stringReverse(str, start, str.length-1);
System.out.println(str);
}
}
~Rajind Ruparathna