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 mademakes easy work of recognizing combining characters for this task.
<lang go>package main
 
Line 562:
"fmt"
"unicode"
"unicode/utf8"
)
 
Line 573 ⟶ 574:
}
 
// reverseCodePoints interprets its argument as UTF-8 and ignores bytes
// argument and return value are UTF-8
// that do not form valid UTF-8. return value is UTF-8.
func reverseCodePoints(s string) string {
r := make([]intrune, len(s))
start := len(s)
for _, c := range s {
start-// quietly skip invalid UTF-8
r[start]if c != cutf8.RuneError {
start--
r[start] = c
}
}
return string(r[start:])
}
 
// reversePreservingCombiningCharacters interprets its argument as UTF-8
// argument and return value are 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 := []intrune(s)
r := make([]intrune, len(p))
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 := ij - 1; k <>= ji; k++-- {
start--
 
r[len(r)-j+k-istart] = p[k]
}
i = j
}
return (string(r[start:]))
}
 
Line 615 ⟶ 627:
r := reverseBytes(s)
fmt.Println("reversed bytes:", []byte(r), r)
fmt.Println("original code points:", []intrune(s), s)
r = reverseCodePoints(s)
fmt.Println("reversed code points:", []intrune(r), r)
r = reversePreservingCombiningCharacters(s)
fmt.Println("combining characters:", []intrune(r), r)
}</lang>
Output:
1,707

edits