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

a programm which removes excess spaces from a string

本文关键字:空格 程序 多余 删除 字符串      更新时间:2023-10-16

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

输入:"qwe(2空格)rt(1空格)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++ 11,那么这样做是多余的-您可以使用正则表达式。像下面这样的代码应该可以做到(未经测试):

#include <regex>
#include <iostream>
#include <string>
using namespace::std;
int main(){
  string a;
  cin >> a;
  regex r(" +");
  a = regex_replace(a,r," ");
  cout << a << endl;
  cout << a.length();
  system("pause");
  return 0;
}

您的代码非常无效。假设下面有一个1,000,000个字符的字符串:

a  a  a  a  a  a  a...

每当你的算法遇到第二个空格时,它就遍历整个字符串,向左移动一个字符。我会尝试另一种方法:

    创建两个迭代器,如realPos和charPos。在开始时将它们设置为0。
  • 创建一个变量,存储到目前为止遇到的一些空间,如spacesSeen。设置为0
  • 现在,当realPos小于整个字符串的长度时:
    • 如果string[realPos] != ' 'charPos != realPos,则分配string[charPos] = string[realPos]。然后将realPoscharPos都加1。设置spaceseen为0
    • 如果string[realPos] == ' 'spacesSeen == 0,则spacesSeen加1,复制字符并推进两个迭代器。
    • 如果string[realPos] == ' 'spacesSeen > 0,则增加spacesSeen,然后只增加realPos
  • 现在charPos标记了你的最终字符串结束的地方,调整字符串大小,这样它就结束了。

用更简单的话说,就是一个一个地复制这些字符,并在复制过程中跳过多个空格。