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

如何不使用find()和index()方法查找子串在母串中的位置?

实现自定义str.find()方法(禁用内置查找方法)

你的目标是复刻str.find()的功能,同时不能使用str.find()、str.index()、str.split()这类内置查找/分割方法。先说说你现有代码的问题:给字符串前后加空格的判断逻辑,会漏掉子串出现在原字符串开头或结尾的情况——比如haystack是"needleabc"或者"abcneedle"时,这种判断就会失效,而且也没法直接拿到正确的索引。

下面是可行的实现方案:

haystack = "haystack"
needle = "needle"

# 处理边界情况:子串为空时返回0
if not needle:
    print(0)
    exit()

haystack_len = len(haystack)
needle_len = len(needle)

# 子串比原串长,直接返回-1
if needle_len > haystack_len:
    print(-1)
else:
    # 遍历所有可能的起始位置
    found_index = -1
    for i in range(haystack_len - needle_len + 1):
        # 截取对应长度的子串对比
        if haystack[i:i+needle_len] == needle:
            found_index = i
            break
    print(found_index)

代码说明:

  • 先处理特殊情况:如果needle是空字符串,按照str.find()的规则返回0;如果needle长度大于原字符串,直接返回-1。
  • 遍历原字符串中所有可能的起始索引(范围是0到len(haystack)-len(needle)),每次截取和needle长度相同的子串进行对比。
  • 找到第一个匹配的位置就记录索引并跳出循环,没找到就保持found_index为-1。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 14:35:19