From ed8c63cc0bf6f83f3deae5b0027274601e3863ab Mon Sep 17 00:00:00 2001 From: l-m <66291634+l1mey112@users.noreply.github.com> Date: Thu, 23 Jun 2022 08:41:42 +1000 Subject: [PATCH] builtin: add a contains_only method on string (#14830) --- vlib/builtin/string.v | 17 +++++++++++++++++ vlib/builtin/string_test.v | 7 +++++++ 2 files changed, 24 insertions(+) diff --git a/vlib/builtin/string.v b/vlib/builtin/string.v index fc4bc78a67..4990522d30 100644 --- a/vlib/builtin/string.v +++ b/vlib/builtin/string.v @@ -1130,6 +1130,23 @@ pub fn (s string) contains_any(chars string) bool { return false } +// contains_only returns `true`, if the string contains only the characters in `chars`. +pub fn (s string) contains_only(chars string) bool { + if chars.len == 0 { + return false + } + for ch in s { + mut res := 0 + for i := 0; i < chars.len && res == 0; i++ { + res += int(ch == unsafe { chars.str[i] }) + } + if res == 0 { + return false + } + } + return true +} + // contains_any_substr returns `true` if the string contains any of the strings in `substrs`. pub fn (s string) contains_any_substr(substrs []string) bool { if substrs.len == 0 { diff --git a/vlib/builtin/string_test.v b/vlib/builtin/string_test.v index ff34c646b4..2a39c189db 100644 --- a/vlib/builtin/string_test.v +++ b/vlib/builtin/string_test.v @@ -447,6 +447,13 @@ fn test_contains_any() { assert !''.contains_any('') } +fn test_contains_only() { + assert '23885'.contains_only('0123456789') + assert '23gg885'.contains_only('01g23456789') + assert !'hello;'.contains_only('hello') + assert !''.contains_only('') +} + fn test_contains_any_substr() { s := 'Some random text' assert s.contains_any_substr(['false', 'not', 'rand'])