c++ - 从字符串中删除多余空格的程序

标签 c++ algorithm

<分区>

我写了一个程序,应该从字符串中删除多余的空格。但它只显示空格前的字符。它找到一个空格并检查其后的字符是否为空格。根据多余的空格,它会将其他字符移到多余的空格上。但是输出非常困惑。

输入:“qwe(2个空格)rt(一个空格)y”

输出:“qwe(一个空格)rt(一个空格)y”

#include <iostream>
#include <stdlib.h>
#include <string>

using namespace std;

int main(){
    string a;
    cin >> a;
    int len = a.length();
    int new_len=len;
    int z,s=0;
    for(int i=0; i<new_len; i++){
        if(a[i]==' '){
            z=i+1;
            s=0;
            //Assigning the number of excess spaces to s.
            while(a[z]==' '){
                s++;
                z++;
            }
            //doing the shifting here.
            if(s>0){
                for(int l=i+1; l<new_len-s; l++){
                    a[l]=a[s+l];
                }
            }
            new_len-=s;
        }

    }
    cout << a << endl;
    cout << a.length();
    system("pause");
    return 0;
}

最佳答案

您的大部分代码都是半无意义的——当您使用普通的字符串提取器 (stream >> string) 时,它会自动跳过所有连续的前导空白,并在第一个位置停止读取空白字符。因此,它几乎已经完成了其余代码要完成的所有工作。这就留下了一个更简单的方法来完成同样的任务:

std::copy(std::istream_iterator<std::string>(std::cin),
          std::istream_iterator<std::string>(),
          std::ostream_iterator<std::string>(std::cout, " "));

这确实有一个问题:它会在输出的末尾 处留下一个额外的空间。如果你不想这样,你可以使用 infix_ostream_iterator我以前发过。这样,您可以将上面的内容更改为如下内容:

std::copy(std::istream_iterator<std::string>(std::cin),
          std::istream_iterator<std::string>(),
          infix_ostream_iterator<std::string>(std::cout, " "));

关于c++ - 从字符串中删除多余空格的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15425256/

相关文章:

c++ - 为什么这个 .c 文件只有一行 "../xx/xx.c"?

c++ - 模板程序不断崩溃

algorithm - 如何计算任意幂/根?

c++ - 检查一个字符串是否是另一个字符串的排列

python - 组合算法挑战

algorithm - 我如何获得特定订单的电源组?

algorithm - 通过用 bmw 替换它来最小化最大 hundai

c++ - 在无尽的 C++ 程序中线程化

c++ - 模板函数中的 volatile 类型推导有什么问题?

c++ - 哪个文件操作更快,读还是写