string: optimize starts_with and ends_with

pull/3785/head
yuyi 2020-02-19 22:18:09 +08:00 committed by GitHub
parent e4179c0008
commit 391da0ba07
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 12 additions and 5 deletions

View File

@ -711,20 +711,27 @@ pub fn (s string) contains(p string) bool {
}
pub fn (s string) starts_with(p string) bool {
idx := s.index(p) or {
if p.len > s.len {
return false
}
return idx == 0
for i := 0; i < p.len; i++ {
if s[i] != p[i] {
return false
}
}
return true
}
pub fn (s string) ends_with(p string) bool {
if p.len > s.len {
return false
}
idx := s.last_index(p) or {
for i := 0; i < p.len; i++ {
if p[i] != s[s.len - p.len + i] {
return false
}
return idx == s.len - p.len
}
return true
}
// TODO only works with ASCII