Pages

Reverse each word in string

Reverse each word in a string

  • We can reverse each word in a given string using for-loop, string methods, string buffer, string builder, and java 8 as well.
Examples:

Input:   keep learners
output: peek srenrael

Input:   abc def
output: cba fed

Program to reverse each word in a string:
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class reverseWordsInString {
public static void main(String[] args) {
String str = "keep learners blogger";

String[] words = str.split("\\s");
// split using space
String revString = "";

for (int i = 0; i <= words.length - 1; i++) {

String word = words[i];
String revWord = "";

for (int j = word.length() - 1; j >= 0; j--) {
revWord += word.charAt(j); // reversing each word
}
revString += revWord + " "; // concat reversed words
}
System.out.println("Reversed rach word in string = " + revString);

System.out.println("<<------------------------------>>");


String revWordSb = "";
for (int i = 0; i <= words.length - 1; i++) {
String word = words[i];

StringBuffer sb = new StringBuffer(word);
revWordSb += sb.reverse() + " ";
}
System.out.println("Reverse each word in string using stringBuffer=" + revWordSb);
System.out.println("<<------------------------------>>");

String revWordSbuilder = "";
for (int i = 0; i <= words.length - 1; i++) {
String word = words[i];

StringBuilder sb = new StringBuilder(word);
revWordSbuilder += sb.reverse() + " ";
}
System.out.println("Reverse each word in string using StringBuilder=" + revWordSbuilder);
System.out.println("<<------------------------------>>");


System.out.print("Reverse each word in string using java8=");

for (int i = 0; i <= words.length - 1; i++) {
String word = words[i];

IntStream.range(0, word.length()). // create index [0 .. s.length - 1]
boxed(). // the next step requires them boxed
sorted(Collections.reverseOrder()). // indices in reverse order
map(j -> String.valueOf(word.charAt(j))).collect(Collectors.toList())
.forEach(a -> System.out.print(a));
System.out.print(" ");
}

}
}
Output:
Reverse each word in string
Reverse each word in string
Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.