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

builtin.string: make trim_left/right() behave correctly

This commit is contained in:
joe-conigliaro 2019-08-26 21:18:58 +10:00 committed by Alexander Medvednikov
parent aa438c7c3f
commit 857cf00caf
2 changed files with 15 additions and 7 deletions

View File

@ -608,22 +608,24 @@ pub fn (s string) trim(c byte) string {
} }
pub fn (s string) trim_left(cutset string) string { pub fn (s string) trim_left(cutset string) string {
mut start := s.index(cutset) if s.len == 0 || cutset.len == 0 {
if start != 0 {
return s return s
} }
for start < s.len - 1 && s[start] == cutset[0] { mut pos := 0
start++ cs_arr := cutset.bytes()
for s[pos] in cs_arr {
pos++
} }
return s.right(start) return s.right(pos)
} }
pub fn (s string) trim_right(cutset string) string { pub fn (s string) trim_right(cutset string) string {
if s.len == 0 { if s.len == 0 || cutset.len == 0 {
return s return s
} }
mut pos := s.len - 1 mut pos := s.len - 1
for s[pos] == cutset[0] { cs_arr := cutset.bytes()
for s[pos] in cs_arr {
pos-- pos--
} }
return s.left(pos+1) return s.left(pos+1)

View File

@ -307,6 +307,9 @@ fn test_trim_left() {
assert s.trim_left(' ') == 'module main' assert s.trim_left(' ') == 'module main'
s = ' module main' s = ' module main'
assert s.trim_left(' ') == 'module main' assert s.trim_left(' ') == 'module main'
// test cutset
s = 'banana'
assert s.trim_left('ba') == 'nana'
} }
fn test_trim_right() { fn test_trim_right() {
@ -314,6 +317,9 @@ fn test_trim_right() {
assert s.trim_right(' ') == 'module main' assert s.trim_right(' ') == 'module main'
s = 'module main ' s = 'module main '
assert s.trim_right(' ') == 'module main' assert s.trim_right(' ') == 'module main'
// test cutset
s = 'banana'
assert s.trim_right('na') == 'b'
} }
fn test_all_after() { fn test_all_after() {