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

不使用内置split函数,按逗号、句号和空格分割字符串并存入列表

不使用内置split函数分割字符串(按逗号、句号、空格)

需求明确:将字符串按逗号“,”、句号“.”和空格“ ”分割为单词列表,不能使用任何内置split函数,且直接通过字符串操作得到无空字符串的结果,无需后续对列表做去空处理。

实现代码

def split_custom(input_str):
    word_list = []
    current_word = []
    # 定义所有分隔符
    separators = {',', '.', ' '}
    
    for char in input_str:
        if char in separators:
            # 只有当前已有单词时,才添加到列表
            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

# 测试示例
test_input = "Hi, Welcome to MK training. I love python."
print(split_custom(test_input))

代码说明

  • 用current_word临时存储正在构建的单词,相比直接字符串拼接效率更高
  • 遍历每个字符时,遇到分隔符就检查current_word是否非空:非空则将其转为字符串加入结果列表,随后重置current_word
  • 遍历结束后额外检查current_word,防止最后一个单词因字符串末尾不是分隔符而被遗漏
  • 整个过程完全通过字符串遍历和字符判断实现,没有使用任何内置split函数,且不会生成空字符串元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 01:58:15