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

不使用.split()与.find()方法实现字符串分割及子串索引查找

功能实现代码及说明

问题排查

你当前的代码存在两个明显问题:

  • 循环中复用了参数名target,传入的目标子串直接被覆盖为字符串的单个字符
  • 没有实现任何子串匹配逻辑,仅遍历输出了原字符串的所有字符

实现思路

因为要求禁止使用split()、find()方法,且需要支持多单词组合的目标子串匹配,我们采用以下逻辑实现:

  1. 手动实现按空格分割单词的逻辑,全程不调用内置split()方法,分别将原字符串、目标子串转换为单词列表
  2. 用滑动窗口匹配的方式,在原单词列表中查找和目标单词列表完全匹配的连续子序列,匹配成功就记录对应的起始索引

可运行代码

def str_to_word_list(input_str):
    # 手动实现字符串按空格分割为单词列表,不使用split()方法
    word_list = []
    current_word = []
    for char in input_str:
        if char == " ":
            if current_word:
                word_list.append("".join(current_word))
                current_word = []
        else:
            current_word.append(char)
    # 处理字符串末尾的最后一个单词
    if current_word:
        word_list.append("".join(current_word))
    return word_list

def position(string, target):
    output = []
    source_words = str_to_word_list(string)
    target_words = str_to_word_list(target)
    target_word_count = len(target_words)
    source_word_count = len(source_words)
    # 遍历范围控制避免索引越界
    for i in range(source_word_count - target_word_count + 1):
        is_match = True
        for j in range(target_word_count):
            if source_words[i+j] != target_words[j]:
                is_match = False
                break
        if is_match:
            output.append(i)
    return output

# 测试用例
test_string = "we dont need no education we dont need no thought control no we dont"
print(position(test_string, "dont"))
print(position(test_string, "we dont"))

输出验证

  • 传入目标子串dont时,输出为[1, 6, 13],符合示例要求
  • 传入目标子串we dont时,输出为[0, 5, 12],符合多单词匹配需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:45:03