Share on Google+Share on Google+

Java reverse words in a string using only loops

Advertisement
In this tutorial, you will learn how to reverse words in a string using loops.

Java reverse words in a string using only loops

In this tutorial, you will learn how to reverse words in a string without using any inbuilt methods like split() etc, StringTokenizer functiom or any extra ordinary function Only loops are allowed.

Example:

public class ReverseWordsUsingLoops {

public char[] reverseWords(char[] c)
{
int i;
int word_start_index = 0; 
for( i=0;i<=c.length;i++)
{
if(i==c.length)
{
reverse(c,word_start_index,i-1);
}
else if(c[i]==' ')
{
reverse(c,word_start_index,i-1);
word_start_index = i+1;
}

}
reverse(c,0,i-2);
return c;
}

public char[] reverse(char[] c,int start, int end)
{
char temp;
while(start<end)
{
temp = c[start];
c[start++]=c[end];
c[end--]=temp;
}
return c;
}

public static void main(String args[]){
ReverseWordsUsingLoops rw = new ReverseWordsUsingLoops();
String s = "Hello World";
System.out.println("Input: "+s);
char[] c = s.toCharArray();
System.out.print("Output: ");
System.out.print(rw.reverseWords(c));
}
}

Output:

Input: Hello World
Output: World Hello

Advertisements

Advertisement

Posted on: November 28, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.