在Racket中查找子字符串的索引

3

我阅读了Racket的字符串库,但没有找到一个与Java/JavaScript的indexOf方法等效的函数。也就是说,是否有一个函数可以返回一个子字符串在较大字符串中第一个字符的索引;最好还能够带有一个可选的起始参数。类似于:

(string-index "foobar" "bar")
;;; returns 3

我希望有像列表中的 member 函数一样的东西。


我认为你不会对像成员一样只检查序列成员的代码感到满意;你想要检查子序列。 - Scott Hunter
2个回答

4

在SRFI 13中有许多字符串操作可用。其中包括 string-contains,它正是您想要的。

#lang racket
(require srfi/13) ; the string SRFI    
(string-contains "foobar" "bar")   ; evaluates to 3

查看更多信息:SRFI 13

顺便提一下,这里有一个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")

2
在Racket中没有这样的原始函数,但是您可以使用正则表达式,例如:regular expressions
(regexp-match-positions "example" "This is an example.")
=> '((11 . 18))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接