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();
}