从字符串变量中删除空格

时间:2014-08-16 20:32:52

标签: c++ linux unix

所以我查找了各种函数以及从字符串中删除空格的方法,但它们似乎都不适合我。这就是我现在所拥有的:

string filename = filenamet;
//remove all whitespace
//filename.erase(remove(filename.begin(), filename.end(), isspace), filename.end());

其中filenamet是一个字符串变量,和filename一样。我已经仔细检查了我的所有包含,所以它们似乎也不是问题。这是我得到的编译器错误:

test.cpp: In function ‘void input(char*, char**)’:
test.cpp:256:68: error: cannot convert ‘std::basic_string<char>::iterator {aka __gnu_cxx::__normal_iterator<char*, std::basic_string<char> >}’ to ‘const char*’ for argument ‘1’ to ‘int remove(const char*)’ filename.erase(remove(filename.begin(), filename.end(), isspace), filename.end());

我也尝试过remove_if而不删除,但后来我得到了这个编译错误:

test.cpp: In function ‘void input(char*, char**)’:
test.cpp:256:71: error: ‘remove_if’ was not declared in this scope
     filename.erase(remove_if(filename.begin(), filename.end(), isspace), filename.end());

非常感谢任何帮助!

4 个答案:

答案 0 :(得分:1)

你也可以试试这个:

   string::iterator iter = filename.begin();
   while ( iter != filename.end() )
   {
      if ( isspace ( *iter ) )
      {
         iter = filename.erase ( iter );
      }
      else
      {
         iter++;
      }
   }

我编译并测试了它,所以它应该可以运行。

答案 1 :(得分:1)

请务必仔细阅读错误!

test.cpp: In function ‘void input(char*, char**)’:
test.cpp:256:68: error: cannot convert 
    ‘std::basic_string<char>::iterator {aka __gnu_cxx::__normal_iterator<char*, std::basic_string<char> >}’ 
     to ‘const char*’ for argument ‘1’ 
     to ‘int remove(const char*)’ 
     filename.erase(remove(filename.begin(), filename.end(), isspace), filename.end());

问题是编译器认为您正在调用此std::remove而不是此std::remove。我猜这个问题就是你忘记了:

#include <algorithm>

因为否则这一行:

filename.erase(remove(filename.begin(), filename.end(), isspace), filename.end());

是从字符串filename中删除所有空格的正确方法。

答案 2 :(得分:0)

#include <algorithm>
#include <cctype>

// One of this two:

s.resize(std::remove_if(s.begin(), s.end(), std::isspace) - s.begin());
s.erase(std::remove_if(s.begin(), s.end(), std::isspace), s.end());

解释

std::remove_if(s.begin(), s.end(), std::isspace)使用s覆盖s的前缀,跳过空白字符。它不会改变字符串的大小,所以如果有任何空格,s的结尾将不受影响并包含可能无用的内容,因此我们使用{{1}修剪它}或std::string::erasestd::string::resize将pass-the-end迭代器返回到新内容,我用它来确定要删除的内容/ std::remove_if的新大小。

答案 3 :(得分:-1)

std::string remove_char(const std::string &input, char to_remove){
    std::string output;
    for(unsigned i=0; i<input.size(); ++i)
        if(input[i]!=to_remove)
            output+=input[i];
    return output;
}
相关问题