Skip to content

Commit 81a1490

Browse files
authored
builtin: add string.split_any/1 (#12720)
1 parent ace6359 commit 81a1490

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

vlib/builtin/string.v

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,36 @@ fn (s string) + (a string) string {
618618
return res
619619
}
620620

621+
// split_any splits the string to an array by any of the `delim` chars.
622+
// Example: "first row\nsecond row".split_any(" \n") == ['first', 'row', 'second', 'row']
623+
// Split a string using the chars in the delimiter string as delimiters chars.
624+
// If the delimiter string is empty then `.split()` is used.
625+
[direct_array_access]
626+
pub fn (s string) split_any(delim string) []string {
627+
mut res := []string{}
628+
mut i := 0
629+
// check empty source string
630+
if s.len > 0 {
631+
// if empty delimiter string using defautl split
632+
if delim.len <= 0 {
633+
return s.split('')
634+
}
635+
for index, ch in s {
636+
for delim_ch in delim {
637+
if ch == delim_ch {
638+
res << s[i..index]
639+
i = index + 1
640+
break
641+
}
642+
}
643+
}
644+
if i < s.len {
645+
res << s[i..]
646+
}
647+
}
648+
return res
649+
}
650+
621651
// split splits the string to an array by `delim`.
622652
// Example: assert 'A B C'.split(' ') == ['A','B','C']
623653
// If `delim` is empty the string is split by it's characters.

vlib/builtin/string_test.v

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,17 @@ fn test_split() {
229229
assert vals[1] == ''
230230
}
231231

232+
fn test_split_any() {
233+
assert 'ABC'.split_any('') == ['A', 'B', 'C']
234+
assert ''.split_any(' ') == []
235+
assert ' '.split_any(' ') == ['']
236+
assert ' '.split_any(' ') == ['', '']
237+
assert 'Ciao come stai? '.split_any(' ') == ['Ciao', 'come', 'stai?']
238+
assert 'Ciao+come*stai? '.split_any('+*') == ['Ciao', 'come', 'stai? ']
239+
assert 'Ciao+come*stai? '.split_any('+* ') == ['Ciao', 'come', 'stai?']
240+
assert 'first row\nsecond row'.split_any(' \n') == ['first', 'row', 'second', 'row']
241+
}
242+
232243
fn test_trim_space() {
233244
a := ' a '
234245
assert a.trim_space() == 'a'

0 commit comments

Comments
 (0)