mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
string: add filter method (#5812)
This commit is contained in:
parent
8674991bac
commit
b5b5176f9b
@ -1382,6 +1382,20 @@ pub fn (s string) map(func fn(byte) byte) string {
|
||||
return tos(res, s.len)
|
||||
}
|
||||
|
||||
pub fn (s string) filter(func fn(b byte) bool) string {
|
||||
mut new_len := 0
|
||||
mut buf := malloc(s.len + 1)
|
||||
for i in 0 .. s.len {
|
||||
mut b := s[i]
|
||||
if func(b) {
|
||||
buf[new_len] = b
|
||||
new_len++
|
||||
}
|
||||
}
|
||||
buf[new_len] = 0
|
||||
return string(buf, new_len)
|
||||
}
|
||||
|
||||
// Allows multi-line strings to be formatted in a way that removes white-space
|
||||
// before a delimeter. by default `|` is used.
|
||||
// Note: the delimiter has to be a byte at this time. That means surrounding
|
||||
|
@ -784,6 +784,18 @@ fn foo(b byte) byte {
|
||||
return b - 10
|
||||
}
|
||||
|
||||
fn test_string_filter() {
|
||||
foo := 'V is awesome!!!!'.filter(fn (b byte) bool {
|
||||
return b != `!`
|
||||
})
|
||||
assert foo == 'V is awesome'
|
||||
assert 'Alexander'.filter(filter) == 'Alexnder'
|
||||
}
|
||||
|
||||
fn filter(b byte) bool {
|
||||
return b != `a`
|
||||
}
|
||||
|
||||
fn test_split_into_lines() {
|
||||
line_content := 'Line'
|
||||
text_crlf := '${line_content}\r\n${line_content}\r\n${line_content}'
|
||||
|
Loading…
Reference in New Issue
Block a user