Skip to content

Instantly share code, notes, and snippets.

@acsellers
Created August 3, 2017 19:11
Show Gist options
  • Save acsellers/26f8f9cfc0cf5ed8353cc1eab4c07219 to your computer and use it in GitHub Desktop.
Save acsellers/26f8f9cfc0cf5ed8353cc1eab4c07219 to your computer and use it in GitHub Desktop.
Golang Reverse String preserving Combining Characters
package main
import (
"fmt"
"unicode"
)
var combining = &unicode.RangeTable{
R16: []unicode.Range16{
{0x0300, 0x036f, 1}, // combining diacritical marks
{0x1ab0, 0x1aff, 1}, // combining diacritical marks extended
{0x1dc0, 0x1dff, 1}, // combining diacritical marks supplement
{0x20d0, 0x20ff, 1}, // combining diacritical marks for symbols
{0xfe20, 0xfe2f, 1}, // combining half marks
},
}
func reverse(s string) string {
sv := []rune(s)
rv := make([]rune, 0, len(sv))
cv := make([]rune, 0)
for ix := len(sv) - 1; ix >= 0; ix-- {
r := sv[ix]
if unicode.In(r, combining) {
cv = append(cv, r)
} else {
rv = append(rv, r)
rv = append(rv, cv...)
cv = make([]rune, 0)
}
}
return string(rv)
}
func main() {
fmt.Println(reverse("Hello World"))
fmt.Println(reverse("👽👶⃠🎃"))
fmt.Println(reverse("H̙̖ell͔o̙̟͚͎̗̹̬ ̯W̖͝ǫ̬̞̜rḷ̦̣̪d̰̲̗͈"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment