From 4974fd09e569c87ce37f9a81050f04c6ed70d38c Mon Sep 17 00:00:00 2001 From: ScriptBoy2077 <84058466+ScriptBoy2077@users.noreply.github.com> Date: Wed, 19 May 2021 17:24:08 +0800 Subject: [PATCH] utf8: reverse() to handle unicode strings (#10133) --- vlib/encoding/utf8/utf8_util.v | 15 +++++++++++++++ vlib/encoding/utf8/utf8_util_test.v | 7 +++++++ 2 files changed, 22 insertions(+) diff --git a/vlib/encoding/utf8/utf8_util.v b/vlib/encoding/utf8/utf8_util.v index 5184c57e6b..a9329ff511 100644 --- a/vlib/encoding/utf8/utf8_util.v +++ b/vlib/encoding/utf8/utf8_util.v @@ -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 */ diff --git a/vlib/encoding/utf8/utf8_util_test.v b/vlib/encoding/utf8/utf8_util_test.v index 4ab3f96513..1724604889 100644 --- a/vlib/encoding/utf8/utf8_util_test.v +++ b/vlib/encoding/utf8/utf8_util_test.v @@ -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界世好你' +}