From 391da0ba074d329afb1a8bfea11529ba2be3d0ba Mon Sep 17 00:00:00 2001 From: yuyi Date: Wed, 19 Feb 2020 22:18:09 +0800 Subject: [PATCH] string: optimize starts_with and ends_with --- vlib/builtin/string.v | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/vlib/builtin/string.v b/vlib/builtin/string.v index 09fda6462f..b024f13b3f 100644 --- a/vlib/builtin/string.v +++ b/vlib/builtin/string.v @@ -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 { - return false + 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