builtin: add a contains_only method on string (#14830)
parent
a7108ff05c
commit
ed8c63cc0b
|
@ -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 {
|
||||
|
|
|
@ -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'])
|
||||
|
|
Loading…
Reference in New Issue