So I was doing some standard programming interview questions and came across this one:
Reverse words in a string (words are separated by one or more spaces)
I thought it would be fun to do it using lambda expressions, but I found it difficult to get right and my solution feels kind of unwieldy and hacky. So now my question is: Is there a more idiomatic solution than mine?
public static String reverseWordsInString(String str)
{
StringBuilder sb = new StringBuilder();
Stream.of(str.split(" ")).forEach(
word -> sb.append(reverseWord(word, !str.endsWith(word)))
);
return sb.toString();
}
public static String reverseWord(String str, boolean trailingSpace)
{
StringBuilder sb = new StringBuilder();
for(int i = str.length() - 1; i >= 0; i--)
{
sb.append(str.charAt(i));
}
sb.append(trailingSpace ? " " : "");
return sb.toString();
}
Your task description is a bit ambiguous. I couldn’t recognize whether you have to reverse the words or reverse the characters of the words. But here are solutions for both:
public static String reverseWordsInString(String str) {
return String.join(" ", Pattern.compile(" +").splitAsStream(str)
.collect(LinkedList::new, LinkedList::addFirst, (a,b)->a.addAll(0, b)));
}
public static String reverseWordCharacters(String str) {
return Pattern.compile(" +").splitAsStream(str)
.map(word->new StringBuilder(word).reverse())
.collect(Collectors.joining(" "));
}
The first one will reverse the words of a string, thus reverseWordsInString("this is an example") will return example an is this, the second one will reverse the characters of each word, so reverseWordCharacters("this is an example") yield siht si na elpmaxe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With