Reverse words in a given String in Java
Let’s see an approach to reverse words of a given String in Java without using any of the String library function Examples:
Input : "Welcome to geeksforgeeks"
Output : "geeksforgeeks to Welcome"
Input : "I love Java Programming"
Output :"Programming Java love I"
Prerequisite: Regular Expression in Java
Java
import java.util.regex.Pattern;
public class Exp {
static String reverseWords(String str)
{
Pattern pattern = Pattern.compile( "\\s" );
String[] temp = pattern.split(str);
String result = "" ;
for ( int i = 0 ; i < temp.length; i++) {
if (i == temp.length - 1 )
result = temp[i] + result;
else
result = " " + temp[i] + result;
}
return result;
}
public static void main(String[] args)
{
String s1 = "Welcome to geeksforgeeks" ;
System.out.println(reverseWords(s1));
String s2 = "I love Java Programming" ;
System.out.println(reverseWords(s2));
}
}
|
Output:
geeksforgeeks to Welcome
Programming Java love I
Time Complexity: O(n), where n is the length of the string.
Auxiliary Space: O(n)
Approach: Without using split() or trim()
By this approach, we can even remove extra trailing spaces and in between the words also.
Basically, this algorithm involves 3 steps.
- If you find white space, there can be two possibilities.
- It might be end of a word or else extra trailing space in between the words.
- if it is not a white space, add the character to temporary word as shown in the below code.
Below is the implementation of above approach.
Java
import java.util.*;
class GFG {
public static String reverseString(String s)
{
StringBuilder ans= new StringBuilder();
String temp = "" ;
for ( int i= 0 ;i<s.length();i++)
{
char ch = s.charAt(i);
if (ch== ' ' )
{
if (!temp.equals( "" ))
{
ans.insert( 0 ,temp+ " " );
}
temp = "" ;
}
else
temp += ch;
}
return ans.toString().substring( 0 ,ans.length()- 1 );
}
public static void main(String[] args) {
String s1= " Welcome to Geeks For Geeks " ;
System.out.println( "Before reversing length of string : " +s1.length());
String ans1=reverseString(s1);
System.out.println( "After reversing length of string : " +ans1.length());
System.out.println( "\"" +ans1+ "\"\n" );
String s2= " I Love Java Programming " ;
System.out.println( "Before reversing length of string : " +s2.length());
String ans2=reverseString(s2);
System.out.println( "After reversing length of string : " +ans2.length());
System.out.println( "\"" +ans2+ "\"" );
}
}
|
Output
Before reversing length of string : 34
After reversing length of string : 26
"Geeks For Geeks to Welcome"
Before reversing length of string : 34
After reversing length of string : 23
"Programming Java Love I"
Time Complexity: O(N) N is length of string
Auxiliary Space: O(1)
You can find the c++ solution for Reverse words in a String here
Last Updated :
29 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...