3 ways to Reversing String In JAVA
This is the most asked question in Java programming interviews, and there are many ways to do it
Published in
1 min readAug 10, 2023
Using Java’s String Buffer’s reverse method:
String str = "Reverse This String";
StringBuffer str1 = new StringBuffer(str);
System. out.println("Reversed String : "+str1.reverse());
Although we can use inbuilt Java methods to reverse the string, it is good to know alternatives of it, so let’s check other ways to reverse a string without using inbuilt functions
2. Reverse String using for loop and character array
This is the traditional way of reversing a string in which we traverse through the array backwards.
String str = "Reverse This String";
char [] strCharArray = str.toCharArray() ;
StringBuffer revr = new StringBuffer();
for(int i=strCharArray.length-1;i>-1;i--){
revr.append(strCharArray[i]);
}
System.out.println("Reversed String : "+revr);
3. Reverse String using reduce function
String str = "Reverse This String";
String reveresed = str.chars().mapToObj(
c -> (char)c).
reduce("",(sa,c)->c+sa,(s1,s2)->s2+s1);System.out.println("Reversed String :"+reveresed);
It’s also common in interviews that they ask to reverse a sentence without disturbing its sequence.
For example Input — Reverse this string. Output — esreveR sihT gnirtS
String str = "Reverse This String";
String words[] = str.split(" ");
StringBuffer strReversed = new StringBuffer();
for(int i=0;i< words.length;i++){
for(int j=words[i].length()-1;j>-1;j--){
char [] wordsCharArray = words[i].toCharArray();
strReversed.append(wordsCharArray[j]);
}
strReversed.append(" ");
}
System.out.print(strReversed);
Give a clap and follow if this article has helped you learn 😊