Skip to content

Commit 4f85b35

Browse files
authored
builtin: add string.split_by_space() (#23651)
1 parent 99a587a commit 4f85b35

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

vlib/builtin/string.v

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1108,6 +1108,18 @@ pub fn (s string) split_into_lines() []string {
11081108
return res
11091109
}
11101110

1111+
// split_by_space splits the string by whitespace (any of ` `, `\n`, `\t`, `\v`, `\f`, `\r`).
1112+
// Repeated, trailing or leading whitespaces will be omitted.
1113+
pub fn (s string) split_by_space() []string {
1114+
mut res := []string{}
1115+
for word in s.split_any(' \n\t\v\f\r') {
1116+
if word != '' {
1117+
res << word
1118+
}
1119+
}
1120+
return res
1121+
}
1122+
11111123
// substr returns the string between index positions `start` and `end`.
11121124
// Example: assert 'ABCD'.substr(1,3) == 'BC'
11131125
@[direct_array_access]

vlib/builtin/string_test.v

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,13 @@ fn test_rsplit_once() ? {
442442
assert ext3 == ''
443443
}
444444

445+
fn test_split_by_space() {
446+
assert 'a b c'.split_by_space() == ['a', 'b', 'c']
447+
assert ' a\t\tb\tc'.split_by_space() == ['a', 'b', 'c']
448+
assert 'a b c \n\r'.split_by_space() == ['a', 'b', 'c']
449+
assert '\ta b \t \tc \r\n'.split_by_space() == ['a', 'b', 'c']
450+
}
451+
445452
fn test_is_bin() {
446453
assert ''.is_bin() == false
447454
assert '0b1'.is_bin() == true

0 commit comments

Comments
 (0)