Reverse every pair of words in a string
Hi, i am trying to create a method that will accept a string, it will then return a string with every pair of words in the first string reversed.
For example, input string: " Hello this is a test string to reverse every pair of words "
output string: " this Hello a is string test reverse to pair every words of"
so far i have below but i am stuck and really need help. I really appreciate it. Thanks
Code :
//
public static String wordPairReverse(String source){
StringTokenizer st = new StringTokenizer(source, " ");
String strReversedLine = "";
char j=0;
while(st.hasMoreTokens()){
while(j<2){
strReversedLine=st.nextToken()+" "+strReversedLine;
j++;
...
}
//
Re: Reverse every pair of words in a string
No need to use StringTokenizer etc.
All this can be done as 1 line inside a for loop.
Play around with a for loop approach, using String.spit() to your advantage.
Re: Reverse every pair of words in a string
I tried this, but i am getting all sorts of errors. Could someone please suggest a better way if possible. Thanks.
//
public static String wordPairReverse(String source){
StringTokenizer st = new StringTokenizer(source, " ");
String strReversedLine = "";
String tempString = "";
String pairs[]= new String[20];
char j=0;
char i=0;
while(st.hasMoreTokens()){
while(j<2){
tempString=st.nextToken()+" "+tempString;
j++;
}
j=0;
pairs[i]=tempString;
i++;
}
while(i>0){
strReversedLine = pairs[i] + " " + strReversedLine;
i--;
}
return strReversedLine;
}
//
Re: Reverse every pair of words in a string
Quote:
I tried this, but i am getting all sorts of errors.
What errors? Post them in their entirety, (and I recommend the get help link in my signature). How would you do this by hand? Write it out on a piece of paper - this often helps wrap ones head around the problem, which then help to lay out the algorithm in code.
Re: Reverse every pair of words in a string
Its telling me out of bounds exception. I have been trying hours now to get this code working but no success. Can someone please suggest the way i should do it please.