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

不使用split()、strip()等函数如何移除字符串中的多余空格

问题原因分析

你现有代码的问题出在拼接规则上:

  • 每次拿到单词都直接拼接result + " ",如果开头是空格(第一个result是空串),就会导致开头多一个空格
  • 遍历到最后一个单词时,末尾也会额外多拼接一个空格,无法自动去除

方案1:修改你现有的多循环逻辑

只需要调整拼接规则,不要每次都强行加空格,只有当output已经有内容(已经加过第一个单词)的时候,再加空格分隔:

string = " apples   bananas orange  "
result = ""
output = ""
i = 0
n = len(string)
while i < n:
    result = ""
    # 提取连续非空格字符(单词)
    while i < n and string[i] != " ":
        result += string[i]
        i += 1
    # 跳过连续空格
    while i < n and string[i] == " ":
        i += 1
    # 拼接逻辑:如果result非空才拼接,已有内容就先加空格
    if result:
        if output:
            output += " "
        output += result

print(output)

运行结果正好是apples bananas orange,符合要求。


方案2:单循环实现

只需遍历一次字符串,通过判断当前字符和已输出内容的最后一个字符,就能控制空格的添加,最后单独处理末尾可能残留的空格即可:

string = " apples   bananas orange  "
output = ""
n = len(string)
for i in range(n):
    current = string[i]
    if current != " ":
        # 非空格字符直接加
        output += current
    else:
        # 只有当已输出内容不为空,且最后一个字符不是空格时,才加一个空格
        if output and output[-1] != " ":
            output += " "
# 处理末尾可能残留的单个空格,切片属于语法不属于内置方法,符合使用要求
if output and output[-1] == " ":
    output = output[:-1]

print(output)

这个实现逻辑更简洁,遍历一次即可完成处理,性能更优。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 06:45:03