How about pushing the string on a stack (word by word) ignoring the space character and popping the contents of the stack ?
3
Anonymous
7 Nov 2009
I used the String.split() function here:
public static String reverseWords1(String sentence) {
// Split string at word separators into string and then output from end.
String[] words = sentence.split(" ");
StringBuilder result = new StringBuilder();
for(int i=words.length-1; i>=0; i--)
result.append(words[i]).append(" ");
return result.toString();
}
and here by doing it more the traditional way:
public static String reverseWords2(String sentence) {
StringBuilder result = new StringBuilder();
int lastwordend = sentence.length()-1;
for (int i = sentence.length()-1; i>=0; i--)
if (sentence.charAt(i) == ' ') {
result.append(sentence.substring(i+1, lastwordend+1)+" ");
lastwordend = i-1;
}
return result.toString();
}
Go backwards through the sentence, looking for delimiters (i.e. space) and collect the word until you find one or run out of string.
There are 2 solutions to this problem. Note that the string is not printed backwards but the words are just printed in reverse order.
First is to push each word of the string onto a stack and then pop them off and print them.
The second solution requires no extra data structures or space. Simply reverse each word in the string (i.e. scan until you hit a space and then start swapping the first and last letters, moving the pointers toward the center of the word until you meet - then repeat for each word). Then once the words are reversed in the string reverse the entire string and you will get the same result as the first solution.
It's also possible to use a BreakIterator to break at word boundaries. That way, it can also work in multiple languages, for the win :-)
Anonymous
28 May 2012
I used perl
my $orgstr="My name is abc";
print "The orignal sentence is: $orgstr\n";
my @tokens= split(' ', $orgstr);
my $revstr;
foreach my $val (@tokens){
$revstr= $val . ' ' . $revstr;
}
print "The reversed sentence is: $revstr\n";