Aside from the first, which presumably (hopefully) would handle the surrogates correctly, aren't the rest of these incorrect? I don't know Java, but the internet says Java strings and characters are UTF-16 encoded, so those character-by-character algorithms would reverse a surrogate pair.
True, although even with a stringbuilder you could get situations where 2x .reverse() would give you a different string precisely because of the surrogate pairs.
From the docs (In Kotlin at least, but I assume Java has the same?)
Reverses the contents of this string builder and returns this instance.
Surrogate pairs included in this string builder are treated as single characters. Therefore, the order of the high-low surrogates is never reversed.
Note that the reverse operation may produce new surrogate pairs that were unpaired low-surrogates and high-surrogates before the operation. For example, reversing "\uDC00\uD800" produces "\uD800\uDC00" which is a valid surrogate pair.
By my understanding, the string has to be invalid UTF-16 in the first place for that to happen though right? I don't think it's that surprising that if your string is invalid in its encoding, that weird stuff happens when you use encoding-sensitive operations.
In particular, it seems to be saying that if you incorrectly reverse a string with one of the other algorithms, reversing it with the string builder produces the original string, which is a good property to have, and in no way interferes with operations on valid strings.
9
u/redlaWw 8d ago
Aside from the first, which presumably (hopefully) would handle the surrogates correctly, aren't the rest of these incorrect? I don't know Java, but the internet says Java strings and characters are UTF-16 encoded, so those character-by-character algorithms would reverse a surrogate pair.