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

builtin: add string.trim_indexes method, that can be used in string.trim, but also separately from it (#16144)

This commit is contained in:
l-m 2022-10-22 20:56:05 +11:00 committed by GitHub
parent b6faf82911
commit a139bed785
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 3 deletions

View File

@ -1413,11 +1413,18 @@ pub fn (s string) trim_space() string {
// trim strips any of the characters given in `cutset` from the start and end of the string.
// Example: assert ' ffHello V ffff'.trim(' f') == 'Hello V'
[direct_array_access]
pub fn (s string) trim(cutset string) string {
if s.len < 1 || cutset.len < 1 {
return s.clone()
}
left, right := s.trim_indexes(cutset)
return s.substr(left, right)
}
// trim_indexes gets the new start and end indicies of a string when any of the characters given in `cutset` were stripped from the start and end of the string. Should be used as an input to `substr()`. If the string contains only the characters in `cutset`, both values returned are zero.
// Example: left, right := '-hi-'.trim_indexes('-')
[direct_array_access]
pub fn (s string) trim_indexes(cutset string) (int, int) {
mut pos_left := 0
mut pos_right := s.len - 1
mut cs_match := true
@ -1438,10 +1445,10 @@ pub fn (s string) trim(cutset string) string {
}
}
if pos_left > pos_right {
return ''
return 0, 0
}
}
return s.substr(pos_left, pos_right + 1)
return pos_left, pos_right + 1
}
// trim_left strips any of the characters given in `cutset` from the left of the string.

View File

@ -538,6 +538,16 @@ fn test_trim() {
assert 'aaabccc'.trim('ac') == 'b'
}
fn test_trim_indexes() {
mut left, mut right := 0, 0
left, right = '- -- - '.trim_indexes(' -')
assert left == 0 && right == 0
left, right = '- hello-world!\t'.trim_indexes(' -\t')
assert left == 2 && right == 14
left, right = 'abc'.trim_indexes('ac')
assert left == 1 && right == 2
}
fn test_trim_left() {
mut s := 'module main'
assert s.trim_left(' ') == 'module main'