1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

utf8: reverse() to handle unicode strings (#10133)

This commit is contained in:
ScriptBoy2077 2021-05-19 17:24:08 +08:00 committed by GitHub
parent 2086e6f1c1
commit 4974fd09e5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 0 deletions

View File

@ -110,6 +110,21 @@ pub fn raw_index(s string, index int) string {
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
*/

View File

@ -68,3 +68,10 @@ fn test_raw_indexing() {
assert utf8.raw_index(a, 7) == 'g'
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'
}