builtin: add a contains_only method on string (#14830)

master
l-m 2022-06-23 08:41:42 +10:00 committed by GitHub
parent a7108ff05c
commit ed8c63cc0b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 0 deletions

View File

@ -1130,6 +1130,23 @@ pub fn (s string) contains_any(chars string) bool {
return false 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`. // 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 { pub fn (s string) contains_any_substr(substrs []string) bool {
if substrs.len == 0 { if substrs.len == 0 {

View File

@ -447,6 +447,13 @@ fn test_contains_any() {
assert !''.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() { fn test_contains_any_substr() {
s := 'Some random text' s := 'Some random text'
assert s.contains_any_substr(['false', 'not', 'rand']) assert s.contains_any_substr(['false', 'not', 'rand'])