3. Reversing letters and words

First, let's reverse only the letters of each word. The solution to this problem can exploit the StringBuilder class. The first step consists of splitting the string into an array of words using a white space as the delimiter (Spring.split(" ")). Furthermore, we reverse each word using the corresponding ASCII codes and append the result to StringBuilder. First, we split the given string by space. Then, we loop the obtained array of words and reverse each word by fetching each character via charAt() in reverse order:

private static final String WHITESPACE = " ";
...
public String reverseWords(String str) {

String[] words = str.split(WHITESPACE);
StringBuilder reversedString = new StringBuilder();

for (String word: words) {
StringBuilder reverseWord = new StringBuilder();

for (int i = word.length() - 1; i >= 0; i--) {
reverseWord.append(word.charAt(i));
}

reversedString.append(reverseWord).append(WHITESPACE);
}

return reversedString.toString();
}

Obtaining the same result in Java 8 functional style can be done as follows:

private static final Pattern PATTERN = Pattern.compile(" +");
...
public static String reverseWords(String str) {

return PATTERN.splitAsStream(str)
.map(w -> new StringBuilder(w).reverse())
.collect(Collectors.joining(" "));
}

Notice that the preceding two methods return a string containing the letters of each word reversed, but the words themselves are in the same initial order. Now, let's consider another method that reverses the letters of each word and the words themselves. Thanks to the built-in StringBuilder.reverse() method, this is very easy to accomplish:

public String reverse(String str) {

return new StringBuilder(str).reverse().toString();
}
For third-party library support, please consider the Apache Commons Lang, StringUtils.reverse().
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.90.182