I read through Racket's string library but couldn't find a function equivalent to Java/JavaScript's indexOf method. That is, is there a function that returns the index of the first character of a substring within a larger string; preferably one that takes an optional start parameter. Something like:
(string-index "foobar" "bar")
;;; returns 3
I'd be happy with something like lists' member function.
There are a lot of string operations available in SRFI 13. Among these are string-contains which does exactly what you want.
#lang racket
(require srfi/13) ; the string SRFI
(string-contains "foobar" "bar") ; evaluates to 3
See more here: SRFI 13
FWIW here is a naive implementation of string-index
(define (string-index hay needle)
(define n (string-length needle))
(define h (string-length hay))
(and (<= n h) ; if the needle is longer than hay, then the needle can not be found
(for/or ([i (- h n -1)]
#:when (string=? (substring hay i (+ i n)) needle))
i)))
(string-index "foobar" "bar")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With