From b5b5176f9b5fc07615246c097e806831576c3b69 Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Sun, 12 Jul 2020 23:37:28 +0530 Subject: [PATCH] string: add filter method (#5812) --- vlib/builtin/string.v | 14 ++++++++++++++ vlib/builtin/string_test.v | 12 ++++++++++++ 2 files changed, 26 insertions(+) diff --git a/vlib/builtin/string.v b/vlib/builtin/string.v index ea8dd27d2d..a133cb534a 100644 --- a/vlib/builtin/string.v +++ b/vlib/builtin/string.v @@ -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 diff --git a/vlib/builtin/string_test.v b/vlib/builtin/string_test.v index d0841c3298..c3c03cd803 100644 --- a/vlib/builtin/string_test.v +++ b/vlib/builtin/string_test.v @@ -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}'