1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

builtin: add string.contains_any() (#5963)

This commit is contained in:
Lukas Neubert 2020-07-29 21:48:50 +02:00 committed by GitHub
parent f269cbdc94
commit f2c639c869
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 4 deletions

View File

@ -743,16 +743,37 @@ pub fn (s string) count(substr string) int {
return 0 // TODO can never get here - v doesn't know that
}
pub fn (s string) contains(p string) bool {
if p.len == 0 {
pub fn (s string) contains(substr string) bool {
if substr.len == 0 {
return true
}
s.index(p) or {
s.index(substr) or {
return false
}
return true
}
pub fn (s string) contains_any(chars string) bool {
for c in chars {
if c.str() in s {
return true
}
}
return false
}
pub fn (s string) contains_any_substr(substrs []string) bool {
if substrs.len == 0 {
return true
}
for sub in substrs {
if s.contains(sub) {
return true
}
}
return false
}
pub fn (s string) starts_with(p string) bool {
if p.len > s.len {
return false

View File

@ -361,6 +361,23 @@ fn test_contains() {
assert 'abc'.contains('')
}
fn test_contains_any() {
assert !'team'.contains_any('i')
assert 'fail'.contains_any('ui')
assert 'ure'.contains_any('ui')
assert 'failure'.contains_any('ui')
assert !'foo'.contains_any('')
assert !''.contains_any('')
}
fn test_contains_any_substr() {
s := 'Some random text'
assert s.contains_any_substr(['false', 'not', 'rand'])
assert !s.contains_any_substr(['ABC', 'invalid'])
assert ''.contains_any_substr([])
assert 'abc'.contains_any_substr([''])
}
fn test_arr_contains() {
a := ['a', 'b', 'c']
assert a.contains('b')
@ -484,7 +501,7 @@ fn test_bytes_to_string() {
buf[2] = `l`
buf[3] = `l`
buf[4] = `o`
}
}
assert string(buf) == 'hello'
assert string(buf, 2) == 'he'
bytes := [`h`, `e`, `l`, `l`, `o`]