Reverse a string: Difference between revisions
→{{header|Go}}: used rune type, also added check for invalid UTF-8.
(adding sas) |
(→{{header|Go}}: used rune type, also added check for invalid UTF-8.) |
||
Line 556:
<lang gema>\L<U1><U>=@{$2}$1</lang>
=={{header|Go}}==
Functions below assume UTF-8 encoding. (The task mentions Unicode but does not specify an encoding.) Strings in Go are not restricted to be UTF-8, but Go has good support for it and works with UTF-8 most natually. As shown below, certain string conversions work in UTF-8 and the range clause over a string works in UTF-8. Go also has a Unicode package in the standard library that
<lang go>package main
Line 562:
"fmt"
"unicode"
"unicode/utf8"
)
Line 573 ⟶ 574:
}
// reverseCodePoints interprets its argument as UTF-8 and ignores bytes
// that do not form valid UTF-8. return value is UTF-8.
func reverseCodePoints(s string) string {
r := make([]
start := len(s)
for _, c := range s {
start--
r[start] = c
}
}
return string(r[start:])
}
// reversePreservingCombiningCharacters interprets its argument as UTF-8
// and ignores bytes that do not form valid UTF-8. return value is UTF-8.
func reversePreservingCombiningCharacters(s string) string {
if s == "" {
return ""
}
p := []
r := make([]
start := len(r)
for i := 0; i < len(p); {
// quietly skip invalid UTF-8
if p[i] == utf8.RuneError {
i++
continue
}
j := i + 1
for j < len(p) && (unicode.Is(unicode.Mn, p[j]) ||
Line 597 ⟶ 609:
j++
}
for k :=
start--
r[
}
i = j
}
return (string(r[start:]))
}
Line 615 ⟶ 627:
r := reverseBytes(s)
fmt.Println("reversed bytes:", []byte(r), r)
fmt.Println("original code points:", []
r = reverseCodePoints(s)
fmt.Println("reversed code points:", []
r = reversePreservingCombiningCharacters(s)
fmt.Println("combining characters:", []
}</lang>
Output:
|