Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find index of substring in Racket

Tags:

string

racket

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.

like image 695
Cristian Avatar asked Oct 28 '25 13:10

Cristian


1 Answers

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")
like image 115
soegaard Avatar answered Oct 31 '25 11:10

soegaard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!