过滤多余的空格

GitHub跳转原题关系图返回列表

使用 split 去除连续空格,再以单个空格 join 重建句子。

OJ: noi_openjudge

题目 ID: ch0107-23

难度:入门

标签:字符串python

日期: 2026-07-30 23:01

题意

将句子中连续的多个空格压缩为一个空格。

思路

无参数 split() 会把连续空白视为一个分隔符,得到单词列表;" ".join(...) 用单个空格重新连接。

代码

Python代码

python
print(" ".join(input().split()))

C++代码

cpp
#include <cstdio>
#include <cstring>

char str[1000];
int cnt=0;
int main(){
    char t;
    while( scanf("%c",&t)!=EOF ){
        str[++cnt] = t;
    }
    bool is_first_blank = true;
    int i;
    for (i=1;i<=cnt;i++){
        if( str[i] == ' ' && is_first_blank){
            printf(" ");
            is_first_blank = false;
        }
        else if ( str[i] != ' '){
            printf("%c",str[i]);
            is_first_blank = true;
        }
    }
    return 0;
}

复杂度

时间和输出空间复杂度均为 O(n)O(n)

总结

压缩分隔符的常用写法是 " ".join(text.split())