faster implementation of prefix/suffix
This commit is contained in:
parent
85e5db38fb
commit
3fc4a64759
|
@ -142,16 +142,20 @@
|
||||||
(and (string? x) (not (zero? (string-length x)))))
|
(and (string? x) (not (zero? (string-length x)))))
|
||||||
|
|
||||||
(define (string-prefix? str prefix)
|
(define (string-prefix? str prefix)
|
||||||
(and
|
(define l1 (string-length str))
|
||||||
(<= (string-length prefix) (string-length str))
|
(define l2 (string-length prefix))
|
||||||
(for/and ([c1 (in-string str)]
|
(let loop ([i 0])
|
||||||
[c2 (in-string prefix)])
|
(cond
|
||||||
(char=? c1 c2))))
|
[(= l2 i) #t] ;; Finished reading all chars in prefix
|
||||||
|
[(= l1 i) #f] ;; Prefix is longer than string
|
||||||
|
[else (and (char=? (string-ref str i) (string-ref prefix i))
|
||||||
|
(loop (add1 i)))])))
|
||||||
|
|
||||||
(define (string-suffix? str suffix)
|
(define (string-suffix? str suffix)
|
||||||
(define offset (- (string-length str) (string-length suffix)))
|
(define l2 (string-length suffix))
|
||||||
(and
|
(define offset (- (string-length str) l2))
|
||||||
(not (negative? offset))
|
(and (not (negative? offset)) ;; Suffix isn't longer than string
|
||||||
(for/and ([c1 (in-string str offset)]
|
(let loop ([i+o offset] [i 0])
|
||||||
[c2 (in-string suffix)])
|
(or (= i l2)
|
||||||
(char=? c1 c2))))
|
(and (char=? (string-ref str i+o) (string-ref suffix i))
|
||||||
|
(loop (add1 i+o) (add1 i)))))))
|
||||||
|
|
Loading…
Reference in New Issue
Block a user