Let us suppose we want to revert the following String "áe".
The unicode for that is "\u0061\u0301\u0065".
The naive aproach of reverting it would be char by char
private static String reverseStringNaive(String s) {
char[] characters = new char[s.length()];
for (int i = s.length() - 1; i >= 0; i--) {
int j = s.length() - i - 1;
characters[j] = s.charAt(i);
}
return new String(characters);
}
which gives us "éa"(\u0065\u0301\u0061) when we hope to get "eá" (\u0065\u0061\u0301). The accute accent "´" should stick together with the "a", not change to the "e".
The following code gives me the expected result for that String:
private static String reverseString(String s) {
char[] characters = new char[s.length()];
for (int i = s.length() - 1; i >= 0; i--) {
int j = s.length() - i - 1;
if (Character.isLetterOrDigit(s.charAt(i)) || Character.isISOControl(s.charAt(i))) {
characters[j] = s.charAt(i);
} else {
characters[j] = s.charAt(i-1);
characters[j+1] = s.charAt(i);
i--;
}
}
return new String(characters);
}
I'm checking if each character is Letter, Digit or ISO Control. If not, I'm assuming it should stick together with the previous character.
The question is, are there other things I should check or worry about? Is my aproach still naive?
charAt
. It’s broken. YOU JUST ILLEGALLY REVERSED ALL YOUR SURROGATES!!!icu.text.BreakIterator.getCharacterInstance
can be used to build something, but I haven’t tried. It’s much easier in Perl with its support for extended grapheme clusters:reverse /(\X)/g
is all it takes. If you don’t do that, you can also invert CRLF combos, enough error.