1
0
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:
Swastik Baranwal 2020-07-12 23:37:28 +05:30 committed by GitHub
parent 8674991bac
commit b5b5176f9b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 0 deletions

View File

@ -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

View File

@ -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}'