You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Racket语言判断第一个字符串是否以第二个字符串开头的实现问题

你当前写的实现仅能判断两个字符串完全相等的场景,无法满足「第一个字符串以第二个字符串开头」的需求,比如当s1为"abcd"、s2为"ab"时,你的代码会错误返回#false。

方案1:直接调用Racket标准库内置函数

Racket的racket/string模块已经提供了原生的string-prefix?接口,完全匹配你需要的功能,可以直接封装使用:

(require racket/string)

(define (string-starts-with? s1 s2)
  (string-prefix? s1 s2))

方案2:手动实现核心逻辑

如果你希望自己实现判断逻辑不依赖内置接口,可以按照如下步骤处理:

  1. 先对比两个字符串的长度,如果第二个字符串长度大于第一个,直接返回假
  2. 截取第一个字符串的前N位(N为第二个字符串的长度),和第二个字符串对比是否相等
    实现代码如下:
(define (string-starts-with? s1 s2)
  (let ([len-s1 (string-length s1)]
        [len-s2 (string-length s2)])
    (cond
      [(> len-s2 len-s1) #false]
      [else (string=? (substring s1 0 len-s2) s2)])))

功能验证测试用例

你可以用以下用例验证功能正确性:

  • (string-starts-with? "hello racket" "hello") → 返回#true
  • (string-starts-with? "test" "test") → 返回#true
  • (string-starts-with? "a" "ab") → 返回#false
  • (string-starts-with? "abcde" "bc") → 返回#false

内容的提问来源于stack exchange,提问作者Hello Kitty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 12:48:04