从字符串变量中删除空格

问题描述 投票:0回答:5

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

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

其中 filenamet 是字符串变量,as 也是 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而不使用remove,但是后来我得到了这个编译器错误:

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());

非常感谢任何帮助!

c++ linux unix
5个回答
3
投票

请务必仔细阅读您的错误!

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


1
投票

您也可以尝试一下:

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

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


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
的末尾将保持不变并包含以前的内容,这可能是无用的,所以我们使用
std::string::resize
 修剪它std::string::erase
std::remove_if
将传递结束迭代器返回到新内容,我用它来确定要删除的内容/
s
的新大小应该是多少)。


0
投票

我刚刚包含了下面的头文件,一切都对我有用。

#include <algorithm>

-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;
}
© www.soinside.com 2019 - 2024. All rights reserved.