Reputation: 1164
I'm working on reversing the string word by word and making sure that all the spaces, tabs and white spaces character etc. are not changed or removed. I have tried few solution using Java, but ending up with no good result. For example , to convert following string
The rule about++[] the input
stream.
And get output like this without removing any white space character.
ehT elur tuoba++[] eht tupni
maerts.
My code
String reverseString(String str) {
StringBuilder temp = new StringBuilder();
StringBuilder result = new StringBuilder();
for (char ch : str.toCharArray()) {
if (Character.isAlphabetic(ch)) {
temp.append(ch);
} else {
result.append(temp.reverse()).append(ch);
temp.delete(0, temp.length());
}
}
result.append(temp);
return result.toString();
}
I getting same result with one issue that word about++[]
, should be ][++tuoba0
where as
it is showing like this tuoba++[]
. Any way to resolve this issue?
Upvotes: 1
Views: 1759
Reputation: 124265
Try changing
if (Character.isAlphabetic(ch)) {
to
if (!Character.isWhitespace(ch)) {
This way you will include all characters that are not whitespaces. Otherwise you will reverse only alphabetic characters which [
]
+
are not.
Upvotes: 3
Reputation: 6462
+
and []
are not alphabetical, so you are treating them the same way you treat whitespace. Character.isWhitespace
can help you solve your problem.
Upvotes: 2