Java Program To Reverse Each Word In A String
========================================================================
public class ReverseEachWordInAString {
public static void main(String[] args) {
String str = "Welcome To Java";
String words[] = str.split(" ");
String reverseString = "";
for (String w : words) {
String reverseWord = "";
for (int i = w.length() - 1; i >= 0; i--) {
reverseWord = reverseWord + w.charAt(i);
}
reverseString = reverseString + reverseWord + " ";
}
System.out.println(reverseString);
}
}
Output:
==============
emocleW oT avaJ
Approach -2
===============
Java Program To Reverse A String Using StringBuilder Class reverse method
public class ReverseEachWordInString2 {
public static void main(String[] args) {
String str = "Welcome To Java";
String words[] = str.split("\\s");
String reverseString = "";
for (String w : words) {
StringBuilder sb = new StringBuilder(w);
sb = sb.reverse();
reverseString = reverseString + sb.toString() + " ";
}
System.out.println(reverseString);
}
}
output:
============
emocleW oT avaJ
Comments
Post a Comment