In this article we are going to learn how to write a java program to reverse each and every word of a given string in java. To reverse the words of a string firstly we will use split(“\\s”) method, by using split(“\\s) we will get all the words of string sentence/phrase in an array then we will reverse each word of an array.
Example
If the input is “My Code” then the output will be “yM edoC”.
If the input is “The Code Data” then the output will be “ehT edoC ataD”.
Java Program to Reverse Words of a Given String
public class ReverseString {
public static void main(String[] args){
String input="The Code Data";
ReverseString rev =new ReverseString();
rev.reverseWordsOfString(input);
}
public void reverseWordsOfString(String input){
String [] arr=input.split("\\s");
String newString="";
for(int i=0;i< arr.length;i++){
newString=newString+reverse(arr[i])+" ";
}
System.out.println("The new String after reversing words of input string is : "+newString);
}
public String reverse(String s){
String str="";
for(int i=s.length()-1;i>=0;i--){
str=str+s.charAt(i);
}
return str;
}
}
Similar Java Tutorials
- Odd Even in Java
- Method to print exception information in Java
- Exception Handling by Using try-catch in Java
- Checked Exception vs Unchecked Exception
- Exception Hierarchy in Java
- Java Exception Handling Interview Questions
- final finally finalize in java
- User Defined Exception in Java
- Exception Handling Keyword in Java
- throw throws in Java
- try with multiple catch block in Java
- Threads in Java
- Thread priority in Java