不使用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
相关产品推荐
相关产品推荐

