Browse Source

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

master
joe-conigliaro 2 years ago
committed by Alexander Medvednikov
parent
commit
857cf00caf
  1. 16
      vlib/builtin/string.v
  2. 6
      vlib/builtin/string_test.v

16
vlib/builtin/string.v

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

6
vlib/builtin/string_test.v

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

Loading…
Cancel
Save