builtin: add string.split_any/1 (#12720)

pull/12723/head
penguindark 2021-12-04 19:13:40 +01:00 committed by GitHub
parent ace63594bf
commit 81a1490e31
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 0 deletions

View File

@ -618,6 +618,36 @@ fn (s string) + (a string) string {
return res return res
} }
// split_any splits the string to an array by any of the `delim` chars.
// Example: "first row\nsecond row".split_any(" \n") == ['first', 'row', 'second', 'row']
// Split a string using the chars in the delimiter string as delimiters chars.
// If the delimiter string is empty then `.split()` is used.
[direct_array_access]
pub fn (s string) split_any(delim string) []string {
mut res := []string{}
mut i := 0
// check empty source string
if s.len > 0 {
// if empty delimiter string using defautl split
if delim.len <= 0 {
return s.split('')
}
for index, ch in s {
for delim_ch in delim {
if ch == delim_ch {
res << s[i..index]
i = index + 1
break
}
}
}
if i < s.len {
res << s[i..]
}
}
return res
}
// split splits the string to an array by `delim`. // split splits the string to an array by `delim`.
// Example: assert 'A B C'.split(' ') == ['A','B','C'] // Example: assert 'A B C'.split(' ') == ['A','B','C']
// If `delim` is empty the string is split by it's characters. // If `delim` is empty the string is split by it's characters.

View File

@ -229,6 +229,17 @@ fn test_split() {
assert vals[1] == '' assert vals[1] == ''
} }
fn test_split_any() {
assert 'ABC'.split_any('') == ['A', 'B', 'C']
assert ''.split_any(' ') == []
assert ' '.split_any(' ') == ['']
assert ' '.split_any(' ') == ['', '']
assert 'Ciao come stai? '.split_any(' ') == ['Ciao', 'come', 'stai?']
assert 'Ciao+come*stai? '.split_any('+*') == ['Ciao', 'come', 'stai? ']
assert 'Ciao+come*stai? '.split_any('+* ') == ['Ciao', 'come', 'stai?']
assert 'first row\nsecond row'.split_any(' \n') == ['first', 'row', 'second', 'row']
}
fn test_trim_space() { fn test_trim_space() {
a := ' a ' a := ' a '
assert a.trim_space() == 'a' assert a.trim_space() == 'a'