Reverse each word of the given sentence.
For this sentence : "This is a beautiful world!";
The output should be : [sihT, si, a, lufituaeb, !dlrow]
----------------See the code below----------------------------------
package test;
import java.util.Arrays;
public class Test2ReverseString {
public static void main(String[] args) {
String givenText = "This is a beautiful world!";
String[] text2convert = givenText.split(" ");
String[] newText = new String[text2convert.length];
for(int i=0;i<text2convert.length;i++) {
System.out.println("Converting this text : "+text2convert[i]);
newText[i]=reverseStr(text2convert[i]);
}
System.out.println("Final Reversed Text array : "+Arrays.toString(newText));
}
public static String reverseStr(String text) {
String revText ="" ;
System.out.println("Text to convert : "+text);
int textlengthMinusOne = text.length()-1;
for(int i=textlengthMinusOne;i>=0;i--) {
revText = revText.concat(Character.toString(text.charAt(i)));
}
System.out.println("Reversed Text : "+revText);
return revText;
}
}
Output:
Converting this text : This
Text to convert : This
Reversed Text : sihT
Converting this text : is
Text to convert : is
Reversed Text : si
Converting this text : a
Text to convert : a
Reversed Text : a
Converting this text : beautiful
Text to convert : beautiful
Reversed Text : lufituaeb
Converting this text : world!
Text to convert : world!
Reversed Text : !dlrow
Final Reversed Text array : [sihT, si, a, lufituaeb, !dlrow]
No comments:
Post a Comment