2013-03-15 124 views
0

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

输入: “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; 
} 
+0

你调试了你的代码吗? – Spook 2013-03-15 05:26:36

+2

这是你想要做什么? http://stackoverflow.com/questions/8362094/replace-multiple-spaces-with-one-space-in-a-string – 2013-03-15 05:26:37

+0

我会咨询[std :: string](http://en.cppreference.com/ w/cpp/string/basic_string),并考虑使用'find_first_of()'和'find_first_not_of()'及其模拟器来更有效地实现它。 – ChiefTwoPencils 2013-03-15 05:28:50

回答

1

大部分代码是半无意义的 - 当您使用普通字符串提取器(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, " ")); 
+0

我不明白这段代码。但它可能是解决方案。 – bbilegt 2013-03-15 07:32:21

1

你的代码是高度无效的。想象一下,下面的字符串包含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。将空格设置为0.
    • 如果string[realPos] == ' 'spacesSeen == 0,则将spacesSeen增加1,复制字符并同时推进两个迭代器。
    • 如果string[realPos] == ' 'spacesSeen > 0,则增加spacesSeen,然后仅增加realPos
  • 现在charPos标志着最后一个字符串结束的位置,调整字符串的大小,使它在那里结束。

简单的说法是:逐个复制字符,并在路上跳过多个空格。

+0

它是有帮助的。 – bbilegt 2013-03-15 07:08:36

1

如果您使用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; 
} 
相关问题