Skip to content

Commit

Permalink
builtin: add string.split_by_space() (#23651)
Browse files Browse the repository at this point in the history
  • Loading branch information
gechandesu authored Feb 4, 2025
1 parent 99a587a commit 4f85b35
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
12 changes: 12 additions & 0 deletions vlib/builtin/string.v
Original file line number Diff line number Diff line change
Expand Up @@ -1108,6 +1108,18 @@ pub fn (s string) split_into_lines() []string {
return res
}

// split_by_space splits the string by whitespace (any of ` `, `\n`, `\t`, `\v`, `\f`, `\r`).
// Repeated, trailing or leading whitespaces will be omitted.
pub fn (s string) split_by_space() []string {
mut res := []string{}
for word in s.split_any(' \n\t\v\f\r') {
if word != '' {
res << word
}
}
return res
}

// substr returns the string between index positions `start` and `end`.
// Example: assert 'ABCD'.substr(1,3) == 'BC'
@[direct_array_access]
Expand Down
7 changes: 7 additions & 0 deletions vlib/builtin/string_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,13 @@ fn test_rsplit_once() ? {
assert ext3 == ''
}

fn test_split_by_space() {
assert 'a b c'.split_by_space() == ['a', 'b', 'c']
assert ' a\t\tb\tc'.split_by_space() == ['a', 'b', 'c']
assert 'a b c \n\r'.split_by_space() == ['a', 'b', 'c']
assert '\ta b \t \tc \r\n'.split_by_space() == ['a', 'b', 'c']
}

fn test_is_bin() {
assert ''.is_bin() == false
assert '0b1'.is_bin() == true
Expand Down

0 comments on commit 4f85b35

Please sign in to comment.