Using a Stack and StringTokenizer seems to be a bit of an overkill here. A more simplified version could be written like this:
public static String reverse(final String input) {
Objects.requireNonNull(input);
final StringBuilder stringBuilder = new StringBuilder();
for (final String part : input.split("\s+")) {
if (!part.isEmpty()) {
if (stringBuilder.length() > 0) {
stringBuilder.insert(0, " ");
}
stringBuilder.insert(0, part);
}
}
return stringBuilder.toString();
}
This uses the ability of split()
to take a String apart based on a given Regex. So the string is split based on a sequence of one or more white-spaces, which matches your initial requirement. Note that split will return an empty array in case input is an empty string.
The for-each loop then works through the array and inserts the part at the beginning of the stringBuilder (except for the first time), which will effectively reverse the array. Most people would probably use a reverse for(i...)
loop here, but because this is a code review I try to be extra correct, and this is the safer version: You cannot cause ArrayIndexOutOfBoundsExceptions with for-each.
Any leading/trailing white-space will cause empty parts to appear in the splitted list, so there is a check for it in the loop. I use isEmpty()
here, as this is in general safer (as in: less chance to do typos) than length() > 0
and benefits from potential, internal optimizations of String in terms of execution speed. You could call trim()
beforehand, but this would cause some unnecessary String operations and creations, so this version is more efficient.
Please also note the check for null
at the beginning. The code would otherwise throw when trying to split on null
, but it is considered good practice to check before-hand, as theoretically (not in this code but in other) you otherwise might leave the system in an undefined state.
I also make use of final
, which allows some compiler optimizations and prevents you from some basic coding mistakes, which is considered good practice.
Testing
It is always a good idea to do some quick testing of the functionality including the basic edge-cases, so here it is:
To check whether or not I do correct white-space removal, I change stringBuilder.insert(0, " ")
to stringBuilder.insert(0, "+")
for the test, to make the white-space visible.
When testing with System.out.println(reverse("the sky is blue"));
the result is:
blue+is+sky+the
The initial requirement is met.
When testing with System.out.println(reverse(" t the sky ist blue "));
the result is:
blue+is+sky+the
Leading, trailing and in-between white-spaces are correctly removed.
When testing with reverse("")
the result is an empty String as expected.
When testing with reverse(null)
a NullPointerException is thrown at the beginning of the function.
How to Reverse a String in Java Word by Word
Today we will learn How to Reverse a String in Java Word by Word and also how to reverse a string in java. So before start learning, we will make you know about reversing a string.
What is reversing a String?
Reversing a string means changing the positions of the characters in such a way that the last character comes in the first position, second last on the second position and so on.
For Example the reverse of learnprogramo is omargorpnrael
There are so many ways to reverse a string we will see it one by one.
1. Converting String into Bytes. |
2. Using the Inbuilt reverse() Method of StringBuilder Class. |
3. By Converting String to Character Array. |
4. By Using toCharArray() Method. |
5. Using ArrayList Object. |
6. Reverse a String word by word. |
7. Reverse a String in Java Using Recursion. |
8. Reverse a String in Java Using For Loop. |
9. Without Using Reverse Function. |
10. Using Unicode Right to Left Override. |
1. Converting String into Bytes
Converting String into Bytes is one of the java methods to reverse a string. In this program, we will use java inbuilt getBytes() method to convert the given string into the bytes[].
Steps to reverse a string by converting string into bytes:
1st Step: First create a temporary byte[] whose length should be equal to the length of the input string.
2nd Step: Now store the bytes in the reverse order into the byte[].
3rd Step: Finally create the new string the byte[] for storing the result.
So let us see how to write a java program to reverse a string using string into Bytes method.
//Learnprogramo import java.io.*; import java.util.*; public class test { public static void main(String[] args) { String input = "learnprogramo"; // getBytes() method to convert string // into bytes[]. byte [] strAsByteArray = input.getBytes(); byte [] result = new byte [strAsByteArray.length]; // Store result in reverse order into the // result byte[] for (int i = 0; i<strAsByteArray.length; i++) result[i] = strAsByteArray[strAsByteArray.length-i-1]; System.out.println(new String(result)); } }
Output:
2. Using the Inbuilt Reverse() Method of StringBuilder Class
In java the String Class do not have a reverse() method so we need to convert the given input string into StringBuilder. this method is done using the append method of the StringBuilder.
This method replaces all the character sequences in the reverse order. At last, the characters of the reversed string are printed by scanning from first to the last index.
//Learnprogramo public class test { public static void main(String[] args) { String input = "Learnprogramo"; StringBuilder input1 = new StringBuilder(); // append a string into StringBuilder input1 input1.append(input); // reverse StringBuilder input1 input1 = input1.reverse(); // print reversed String System.out.println(input1); } }
Output:
3. By Converting String to Character Array
In this program, we will make use of character array for reversing a string. We will use the inbuilt method toCharAt().
Steps to Convert String to Character Array:
1st Step: First read the input String using scanner object scan.nextline() and store that string in the variable str.
2nd Step: Initialize char[]ch.
3rd Step: Here j is the length of the array, and the for loop starts as i>0. Loop prints the character from the index i-1 of array ch.
4th Step: Now print characters from the last index of char array.
//Learnprogramo import java.util.*; public class test { public static void main(String[]args) { String str; Scanner scan=new Scanner(System.in); System.out.print("Enter a string : "); str=scan.nextLine(); char[] ch=str.toCharArray(); System.out.print("Reverse of a String is :"); int j=ch.length; for(int i=j;i>0;i--) { System.out.print(ch[i-1]); } } }
Output:
4. Using toCharArray() Method
In this program, we are going to use another inbuilt method called toCharArray(). In this method, we first scan the character array from both the sides i.e from the start and the last index simultaneously.
Step to Use toCharArray() Method:
1st Step: First set the first index to 0 and right index to -1 (length of the string).
2nd Step: Now swap the characters of the start index with the last index one by one.
3rd Step: Increase the left index by 1 using left++ and simultaneously decrease the right index by 1 using right++.
4th Step: Now, Continue till left becomes less than or equal to the right.
//Learnprogramo public class test { public static void main(String[] args) { String input = "learnprogramo"; char[] temparray = input.toCharArray(); int left, right; right = temparray.length-1; for (left=0; left < right ; left++ ,right--) { // Swap values of left and right char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right]=temp; } for (char c : temparray) System.out.print(c); System.out.println(); } }
Output:
5. Using ArrayList Object
In this program, we will use the ArrayList Object for reversing the string. First, we will convert the given string in the character array using java inbuilt method toCharArray(). After converting add all the characters in the ArrayList object. The Collection class reverse() method takes the list object.
For reversing the string we need to pass an ArrayList object which is in the form of a list of the characters.
Steps for Using ArrayList Object:
1st Step: First, copy all the content to the ArrayList Object.
2nd Step: Now create an object using ListIterator() method on ArrayList Object.
3rd Step: ListIterator is used to print the reversed list on the screen.
//Learnprogramo import java.util.*; public class test { public static void main(String[] args) { String input = "learnprogramo"; char[] hello = input.toCharArray(); List<Character> programo = new ArrayList<>(); for (char c: hello) programo.add(c); Collections.reverse(programo); ListIterator li = programo.listIterator(); while (li.hasNext()) System.out.print(li.next()); } }
Output:
6. How to Reverse a String Word by Word
In this program, we will accept a string from the user and then print the reversed string on the screen.
Steps to Reverse a String Word by Word:
1st Step: Accept the input string from the user using a scanner object and store the input string in variable str.
2nd Step: Convert the string into char array using the method toCharArray() and then initialize to char[]ch.
3rd step: add ch[0] to the string word if the given block add the characters to the string word until we get the space.
4th Step: If space is found then else block is executed to reverse the word.
5th Step: the 2nd for loop is used to reverse the last word read by the else block.
//Learnprogramo import java.util.*; public class test { public static void main(String[ ] arg) { String str; String word=""; Scanner scan=new Scanner(System.in); System.out.print("Enter a string : "); str=scan.nextLine(); char[] ch=str.toCharArray(); for(int i=0;i<(ch.length);i++) { if(ch[i]!=' ') { word=word+ch[i]; } else { for(int c=word.length();c>0;c--) { System.out.print(word.charAt(c-1)); } System.out.print(" "); word=""; } } System.out.println("Reverse String is="); for(int c=word.length();c>0;c--) { System.out.print(word.charAt(c-1)); } } }
Output:
7. Reverse a String in Java Using Recursion
Recursion is nothing but the function calls itself directly or indirectly. In this program, we will write a recursive method to reverse the string.
Steps to Reverse a String in Java Using Recursion:
1st Step: Create an object Using a Class StringRecursion r.
2nd Step: Now read the String using Scanner class and store it in variable s.
3rd Step: We have called the reverse method r.rev(s) and the reverse of the string is done.
4th Step: Now the Reverse String is Printed.
//Learnprogramo import java.util.*; public class test { String rev(String str) { if(str.length() == 0) return " "; return str.charAt(str.length()-1) + rev(str.substring(0,str.length()-1)); } public static void main(String[ ] args) { test r=new test(); Scanner sc=new Scanner(System.in); System.out.print("Enter the string : "); String s=sc.nextLine(); System.out.println("Reversed String: "+r.rev(s)); } }
Output:
8. Reverse a String in Java Using For Loop
In this program, we will use for loop to reverse a string in java. The for loop in program iterates from j=length of the string to j>0. Now it prints the character of the string from the index (i-1) and the reverse string is printed on the screen.
import java.util.*; public class test { public static void main(String[ ] arg) { String str; char ch; Scanner sc=new Scanner(System.in); System.out.print("Enter a string : "); str=sc.nextLine(); System.out.println("Reverse of a String '"+str+"' is :"); for(int j=str.length();j>0;--j) { System.out.print(str.charAt(j-1)); } } }
Output:
9. How to Reverse a String in Java Without Using Reverse Function
Now we will write a program to reverse a String in java without using a reverse function using while loop.
This while loop executes until the condition i>0 becomes false.
import java.util.*; public class test { public static void main(String[ ] arg) { String str; Scanner scan=new Scanner(System.in); System.out.print("Enter a string : "); str=scan.nextLine(); System.out.println("Reverse of a String '"+str+"' is :"); int i=str.length(); while(i>0) { System.out.print(str.charAt(i-1)); i--; } } }
Output:
10. Using Unicode Right to Left Override
In this program, we will use Unicode Right to Left Override Method to Reverse a String in java. Let us see how the program is written with output.
//Learnprogramo import java.util.*; public class test { // Function to reverse a string in Java by Unicode // Right-to-left Override (RLO) character public static String reverse(String str) { return "u202E" + str; } public static void main (String[] args) { String str = "Learnprogramo"; // string is immutable str = reverse(str); System.out.println("Reverse of the given string is : " + str); } }
Output:
Conclusion:
we have discussed all the java methods to reverse a string. Hope you understand all the methods and if you have any doubt then please feel free to mention in the below comment box.
Also Read:
- Program to print number pattern in java.
- Java Program to Print Star Pattern.
learnprogramo@gmail.com2022-04-07T06:08:30+00:00
Related Posts
How to Reverse a String in Java is one of the popular interview questions, but the interviewer might add some twist to it by asking you to write the code without using the reverse() method, recursion, etc. In this article, we will learn the possible ways of reversing a string in Java. We will look into techniques of reversing a single word and group of words in a sentence [Word by Word]
Method 1: Using reverse() function — Using StringBuilder (or) StringBuffer
This is the easiest way of reversing a String, we can use reverse() method of either StringBuilder (or) StringBuffer.
Note: StringBuilder can give a better performance as it is not Synchronized. StringBuffer is Synchronized
import java.util.Scanner; public class StringReverse { public static void main(String[] args) { String reverseString = ""; System.out.println("Enter string to reversed"); //Read the input from the user Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); //Pass input to constructor of StringBuilder StringBuilder inputStr = new StringBuilder(input); //Use reverse() method to reverse the String reverseString = inputStr.reverse().toString(); System.out.println("Original String : "+input); System.out.println("Reversed String : "+reverseString); } }
-
- Get the input string from the user and pass it to the constructor of the StringBuilder.
- Use the reverse() method of the StringBuilder class to get the reversed String.
Output:
Method 2: Reverse String Using charAt()
import java.util.Scanner; public class StringReverse { public static void main(String[] args) { String reverseString = ""; System.out.println("Enter string to reversed"); //Read the input from the user Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); //Convert input to inputArray using toCharArray() char[] inputArray = input.toCharArray(); for(int i=inputArray.length-1;i>=0;i--) { reverseString = reverseString+inputArray[i]; } System.out.println("Original String : "+input); System.out.println("Reversed String : "+reverseString); } }
- Get the input string from the user and convert the input string into a character array inputArray using toCharArray() method
- Iterate the inputArray from end to start, each time append it to the reverseString.
Output:
Enter string to reversed JavaInterviewPoint Original String : JavaInterviewPoint Reversed String : tnioPweivretnIavaJ
Method 3: using Recursion
package com.javainterviewpoint; import java.util.Scanner; public class StringReverse { public static void main(String[] args) { String reversedString = ""; System.out.println("Enter string to reversed"); //Read the input from the user Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); reversedString = reverseString(input); System.out.println("Original String : "+input); System.out.println("Reversed String : "+reversedString); } public static String reverseString(String input) { if(input.isEmpty()) return input; //Call reverseString() function recursively return reverseString(input.substring(1)) + input.charAt(0); } }
- Get the input string from the user and pass the input string to the reverseString() method.
- In the reverseString() method, we will be recursively subString() the first character of the input String and append it to the end using charAt() method.
Method 4: Using Stack
import java.util.Scanner; import java.util.Stack; public class StringReverse { public static void main(String[] args) { StringBuilder reverseString = new StringBuilder(); System.out.println("Enter string to reversed"); // Read the input from the user Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); // Create a stack of characters Stack<Character> stack = new Stack<Character>(); // Push each character into the stack for (int i = 0; i < input.length(); i++) { stack.push(input.charAt(i)); } // pop each characters from the stack until it is empty while (!stack.empty()) { reverseString.append(stack.pop()); } System.out.println("Original String : "+input); System.out.println("Reversed String : "+reverseString); } }
- Get the input string from the user.
- Create a Stack of Character and push each character of the input string into the stack.
- Pop each character from the stack until it is empty and append it to the reverseString.
Method 5: Using Collections reverse() method
- Get the input string from the user
- Create a List of Character (characterList) and push each character of the input string into the characterList.
- Use Collections.reverse() method to reverse the elements of the characterList
- Iterate the characterList from end to start, each time append it to the reverseString
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class StringReverse { public static void main(String[] args) { StringBuilder reverseString = new StringBuilder(); System.out.println("Enter string to reversed"); // Read the input from the user Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); //Create a list of characters List<Character> characterList = new ArrayList<Character>(); //Push each characters into the characterList for(Character c : input.toCharArray()) { characterList.add(c); } //Reverse the List using Collections.reverse() Collections.reverse(characterList); //Convert ArrayList to String for(Character c : characterList) { reverseString.append(c); } System.out.println("Original String : "+input); System.out.println("Reversed String : "+reverseString); } }
Java Reverse String Word by Word
All the above methods will work good for a single word, lets now learn how to reverse a string in Java word by word,
We will reverse each word in a sentence.
Method 1: Using StringBuffer
- Get the input string from the user
- Using split() method split the sentence into words and save them to a String array (words)
- Iterate through the String array and use reverse() method of the StringBuffer class to reverse the String and keep appending the reversedString.
package com.javainterviewpoint; import java.util.Scanner; public class StringReverse { public static void main(String[] args) { String reverseString = ""; System.out.println("Enter string to reversed"); //Read the input from the user Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); // Split sentence into seperate words String[] words = input.split(" "); // Iterate the String array for(String word : words) { // Append each reversed Words reverseString = reverseString + new StringBuilder(word).reverse().toString()+" "; } System.out.println("Original String : "+input); System.out.println("Reversed String : "+reverseString); } }
Output:
Enter string to reversed Hello World Original String : Hello World Reversed String : olleH dlroW
Method 2: Using charAt()
- Get the input string from the user
- Using split() method split the sentence into words and save them to a String array (words)
- Iterate through the String array and convert each word into a character array using toCharArray() method
- Iterate through the character array in the decreasing order and each time append the character to the reverseString
package com.javainterviewpoint; import java.util.Scanner; public class StringReverse { public static void main(String[] args) { String reverseString = ""; System.out.println("Enter string to reversed"); //Read the input from the user Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); // Split sentence into seperate words String[] words = input.split(" "); // Iterate the String array for(String word : words) { //Convert input to inputArray using toCharArray() char[] inputArray = word.toCharArray(); for(int i=inputArray.length-1; i>=0; i--) { reverseString = reverseString+inputArray[i]; } reverseString = reverseString + " "; } System.out.println("Original String : "+input); System.out.println("Reversed String : "+reverseString); } }
- Given a string in java, reverse the string word by word.
- Let us look into couple of examples to understand problem statement.
- Example 1:
- String inputString = “Girl Proposes Boy”
- reverse(inputString) should be “Boy Proposes Girl”
- Example 2:
- String inputString = “Hell To Heaven”
- reverse(inputString) should be “Heaven To Hell”
- Example 1:
1. Algorithm: Reverse string word by word (java/ stack /stringbuilder)
- Reverse String using StringBuilder
- Split the input string using space delimiter.
- Start appending the string from end .
- We will get string reversed word wise.
- Reverse String using Stack.
- Split the input string using space delimiter.
- Iterate through the string array (result of previous step) & push each string to stack.
- Pop each string element from stack and concatenate the string.
- We we get the desired output.
Fig 1: Reverse String word by word
2. Program: Reverse string word by word (java/stack/stringbuilder /example)
package org.learn; import java.util.Scanner; import java.util.Stack; import java.util.regex.Pattern; public class ReverseWordsInString { public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { System.out.printf("1. Enter string to reverse : "); String inputString = scanner.nextLine(); if (inputString == null || inputString.length() == 0) { System.out.println("Enter the valid string"); return; } String reverse = reverseStringWordWise(inputString); System.out.printf("2. Reverse string using StringBuilder is : %s", reverse); reverse = reverseStringWordWise_Stack(inputString); System.out.printf("n3. Reverse string using stack is : %s", reverse); } } private static String reverseStringWordWise(String inputString) { String[] arrString = inputString.trim().split(Pattern.quote(" ")); StringBuilder builder = new StringBuilder(); int length = arrString.length; while (--length >= 0) { builder.append(arrString[length]).append(" "); } return builder.toString(); } private static String reverseStringWordWise_Stack(String inputString) { String[] arrString = inputString.trim().split(Pattern.quote(" ")); Stack<String> stack = new Stack<>(); for(String input : arrString) { stack.push(input); } StringBuilder builder = new StringBuilder(); while( !stack.isEmpty()) { builder.append(stack.pop()).append(" "); } return builder.toString(); } }
3. Output: Reverse string word by word (java/stack/stringbuilder /example)
1. Enter string to reverse : Girl Proposes Boy 2. Reverse string using StringBuilder is : Boy Proposes Girl 3. Reverse string using stack is : Boy Proposes Girl 1. Enter string to reverse : Hell To Heaven 2. Reverse string using StringBuilder is : Heaven To Hell 3. Reverse string using stack is : Heaven To Hell
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
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 This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Like Article
Save Article
In this section, we reverse a string in Java word by word.
Example 1: Reverse a string word by word using recursion
Output:
Example 2: Reverse a string word by word by using for loop
Output:
For Videos Join Our Youtube Channel: Join Now
Feedback
- Send your Feedback to [email protected]
Help Others, Please Share
Reverse A String In Java – Here, we have discussed the various methods to reverse a string using java. The compiler has been added so that you can execute the programs by yourself, alongside suitable examples and sample outputs. The methods are as follows:
The following program to find reverse a string has been written in five different ways. If you do have any doubts please do let us know. If you need expert help with doing your java homework assigned in college or university – please visit this website.
- Java program to find a reverse a string – Using Static Method
- Using Array
- Using Recursion – In case if you have no idea check out the complete guide here.
- Using While Loop
- Using For Loop – Tutorial With Examples
- Using Word by Word
Reverse A String – Using Static Method
1) String reverse(String s) is the static method This method contains the logic to reverse the string.
2) Create the object for the class ReverseofaString and call the static method with the object as rev.reverse(str)) by passing the given string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.Scanner; class ReverseofaString { public static void main(String[] arg) { ReverseofaString rev=new ReverseofaString(); Scanner sc=new Scanner(System.in); System.out.print(«Enter a string : «); String str=sc.nextLine(); System.out.println(«Reverse of a String is : «+rev.reverse(str)); } static String reverse(String s) { String rev=«»; for(int j=s.length();j>0;—j) { rev=rev+(s.charAt(j—1)); } return rev; } } |
Output:
Enter a string : String Reverse of a String is : gnirtS |
Java Code Reverse A String – Using Array
1) We are using a character array to reverse the given string.
2) Read the entered string using scanner object scan.nextLine() and store it in the variable str. We are converting the string a to character array the string class method toCharArray() and initialized to char[] ch.
3) j=length of the array, for loop iterates from i=length of the array to i>0. The loop prints the character which is at the index i-1 of the array “ch” i.e. it prints the characters from the last index of the char array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.Scanner; class ReverseofaString { public static void main(String[ ] arg) { String str; Scanner scan=new Scanner(System.in); System.out.print(«Enter a string : «); str=scan.nextLine(); char[] ch=str.toCharArray(); System.out.println(«Reverse of a String is :»); int j=ch.length; for(int i=j;i>0;i—) { System.out.print(ch[i—1]); } } } |
Output:
Enter a string : computer science Reverse of a String is : ecneics retupmoc |
Using Recursion
1) A method that calls itself is recursive. In this program reverse(String s) is recursive.
2) Create the object for the class ReverseofaString rev. Read the entered string using sc.nextLine() and store it in the string variable str. Call the reverse method as rev.reverse(str).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.Scanner; class ReverseofaString { String reverse(String s) { if(s.length() == 0) return » «; return s.charAt(s.length()—1) + reverse(s.substring(0,s.length()—1)); } public static void main(String[ ] arg) { ReverseofaString rev=new ReverseofaString(); Scanner sc=new Scanner(System.in); System.out.print(«Enter a string : «); String str=sc.nextLine(); System.out.println(«Reverse of a String :»+rev.reverse(str)); } } |
Output:
Enter a string : enter Reverse of a String :retne |
Using While Loop
1) Here i=length of the given string. While loop iterates until the condition i>0 is false, i.e. if the length of the string is zero then cursor terminates the loop.
2) While loop prints the character of the string which is at the index (i-1) until i>0. Then we will get the reverse of a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.Scanner; class Reverse { public static void main(String[ ] arg) { String str; Scanner scan=new Scanner(System.in); System.out.print(«Enter a string : «); str=scan.nextLine(); System.out.println(«Reverse of a String ‘»+str+«‘ is :»); int i=str.length(); while(i>0) { System.out.print(str.charAt(i—1)); i—; } } } |
Output:
Enter a string : kankesh Reverse of a String ‘kanakesh’ is : hsekanak |
Using For Loop
1) For loop iterates from j=length of the string to j>0.
2) It prints the character of the string which is at the index (i-1), then we will get reverse of a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.Scanner; class ReverseofaString { public static void main(String[ ] arg) { String str; char ch; Scanner sc=new Scanner(System.in); System.out.print(«Enter a string : «); str=sc.nextLine(); System.out.println(«Reverse of a String ‘»+str+«‘ is :»); for(int j=str.length();j>0;—j) { System.out.print(str.charAt(j—1)); } } } |
Output:
Enter a string : java Reverse of a String ‘java’ is : avaj |
Word by Word
1) Read the string using scanner object scan.nextLine() and store it in the variable str. We are converting the string into the char array using the string class method toChatArray(), and initialized to char[] ch.
2) The 1st for loop iterates from i=0 to i< length of the array.
a) If ch[i]!=’ ‘ then adding ch[0] to the string word. If block adds the characters to the string word until we will get space i.e. word contains the 1st word.
b) If we get space then the else block to reverse the word which is read using else block.
3) 2nd for loop reverse the last word which is read by else block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import java.util.Scanner; class ReverseofaString { public static void main(String[ ] arg) { String str; String word=«»; Scanner scan=new Scanner(System.in); System.out.print(«Enter a string : «); str=scan.nextLine(); char[] ch=str.toCharArray(); for(int i=0;i<(ch.length);i++) { if(ch[i]!=‘ ‘) { word=word+ch[i]; } else { for(int c=word.length();c>0;c—) { System.out.print(word.charAt(c—1)); } System.out.print(» «); word=«»; } } for(int c=word.length();c>0;c—) { System.out.print(word.charAt(c—1)); } } } |
Output:
Enter a string : reverse programme esrever emmargorp |
Given an input string, reverse the string word by word.
For example, given s = «the sky is blue», return «blue is sky the».
Java Solution
This problem is pretty straightforward. We first split the string to words array, and then iterate through the array and add each element to a new string. Note: StringBuilder should be used to avoid creating too many Strings. If the string is very long, using String is not scalable since String is immutable and too many objects will be created and garbage collected.
class Solution { public String reverseWords(String s) { if (s == null || s.length() == 0) { return ""; } // split to words by space String[] arr = s.split(" "); StringBuilder sb = new StringBuilder(); for (int i = arr.length - 1; i >= 0; --i) { if (!arr[i].equals("")) { sb.append(arr[i]).append(" "); } } return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1); } }
Category >> Algorithms
If you want someone to read your code,
please put the code inside <pre><code>
and
</code></pre>
tags. For example:
<pre><code> String foo = "bar"; </code></pre>