Reverse the given string from start to end .
Example:
Original String : Proedu provides tutorials and interview questions
Reverse String : questions interview and tutorials provides Proedu
Example – Program to Reverse the string from start to end
public class ReverseString {
public static void main(String[] args)
{
String originalString="Proedu provides tutorials and interview questions";
System.out.print("Original String: ");
System.out.println(originalString);
String sArray[] = originalString.split(" ");
String reverseString = "";
for (int i = sArray.length - 1; i >= 0; i--) {
reverseString += sArray[i] + " ";
}
System.out.print("Reversed String: ");
System.out.print(reverseString);
}
}
Output
Original String: Proedu provides tutorials and interview questions Reversed String: questions interview and tutorials provides Proedu
Reverse the individual words of the given string one by one.
Example:
Original String : Proedu provides tutorials and interview questions
Reverse String : udeorP sedivorp slairotut dna weivretni snoitseuq
Example – Reverse the individual words Using StringBuilder
public class ReverseWord {
public static String reverseWordMethod(String originalStr) {
System.out.println("Original String : "+originalStr);
String words[] = originalStr.split("\\s");
String reverseWord = "";
for (String w : words) {
StringBuilder sb = new StringBuilder(w);
sb.reverse();
reverseWord += sb.toString() + " ";
}
return reverseWord.trim();
}
public static void main(String[] args) {
String reverseString= ReverseWord.reverseWordMethod("Proedu provides tutorials and interview questions");
System.out.println("Reverse String : "+reverseString);
}
}
Output
Original String : Proedu provides tutorials and interview questions Reverse String : udeorP sedivorp slairotut dna weivretni snoitseuq
Example – Reverse the individual words
public class ReverseWord
{
public void reverseWordMethod(String originalStr)
{
String[] words = originalStr.split(" ");
String reversedString = "";
for (int i = 0; i < words.length; i++)
{
String word = words[i];
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
reversedString = reversedString + reverseWord + " ";
}
System.out.println("Original String : "+originalStr);
System.out.println("Reverse String : "+reversedString);
}
public static void main(String[] args)
{
ReverseWord rw = new ReverseWord();
rw.reverseWordMethod("Proedu provides tutorials and interview questions");
}
}
Output
Original String : Proedu provides tutorials and interview questions Reverse String : udeorP sedivorp slairotut dna weivretni snoitseuq