utf8: reverse() to handle unicode strings (#10133)
parent
2086e6f1c1
commit
4974fd09e5
|
@ -110,6 +110,21 @@ pub fn raw_index(s string, index int) string {
|
||||||
return r[index].str()
|
return r[index].str()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// reverse - returns a reversed string.
|
||||||
|
// example: utf8.reverse('你好世界hello world') => 'dlrow olleh界世好你'.
|
||||||
|
pub fn reverse(s string) string {
|
||||||
|
len_s := utf8.len(s)
|
||||||
|
if len_s == 0 || len_s == 1 {
|
||||||
|
return s.clone()
|
||||||
|
}
|
||||||
|
mut str_array := []string{}
|
||||||
|
for i in 0..len_s {
|
||||||
|
str_array << utf8.raw_index(s, i)
|
||||||
|
}
|
||||||
|
str_array = str_array.reverse()
|
||||||
|
return str_array.join('')
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Conversion functions
|
Conversion functions
|
||||||
*/
|
*/
|
||||||
|
|
|
@ -68,3 +68,10 @@ fn test_raw_indexing() {
|
||||||
assert utf8.raw_index(a, 7) == 'g'
|
assert utf8.raw_index(a, 7) == 'g'
|
||||||
assert utf8.raw_index(a, 8) == '!'
|
assert utf8.raw_index(a, 8) == '!'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn test_reversed() {
|
||||||
|
a := '我是V Lang!'
|
||||||
|
b := '你好世界hello world'
|
||||||
|
assert utf8.reverse(a) == '!gnaL V是我'
|
||||||
|
assert utf8.reverse(b) == 'dlrow olleh界世好你'
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue