如何从字符串中删除标点符号

时间:2015-02-16 02:43:24

标签: c++ string

我正在寻找有关读取包含标点符号的字符串的代码的帮助,并输出省略了标点符号的内容。我访问了此链接C++ Remove punctuation from String我相信我的代码是可靠的。当我编译代码时,它会提示输入字符串。然而,在输入字符串并按下回车后,没有任何事情发生,之后没有输出我已经广泛调整了代码,但无济于事。

int main(){
    string line;
    cout <<"Please Enter a line"<< endl;
    while(getline(cin, line)){
        for(decltype(line.size()) index = 0; index != line.size() && !isspace(line[index]); ++index){        
            if (ispunct(line[index])){
                line.erase(index--,1);
                line[index] = line.size();
            }
        }
    }
    cout<< line << endl;
    return 0;
}

3 个答案:

答案 0 :(得分:1)

你正在使这个方式更复杂(decltype?为此?)而不是它需要的。尝试:

int main()
{
    std::string line;
    std::cout <<"Please Enter a line"<< std::endl;
    while(std::getline(std::cin, line)){
        const char* s = line.c_str();
        while(*s){
            if (!ispunct(*s)){
                std::cout << *s;  // not as slow as you would think: buffered output
            }
            ++s;
        }
        std::cout << std::endl; // flush stdout, that buffering thing
    }
}

更简单通常更好。作为副作用,这也应该快得多。

答案 1 :(得分:0)

这可以在没有任何循环的情况下完成。只需使用算法函数即可。

一般情况下,如果您有一个容器,并且想要从容器中删除满足特定条件的项目,那么如果您正在写手,则需要使用长(也许是错误的)方法你正在做的编码循环。

以下是算法函数的使用示例,即std::remove_if

#include <algorithm>
#include <cctype>
#include <string>
#include <iostream>

using namespace std;

int main()
{
   std::string s = "This is, a, string: with ! punctuation.;";
   s.erase(std::remove_if(s.begin(), s.end(), ::ispunct), s.end());
   cout << s;
}

直播示例:http://ideone.com/Q6A0vJ

答案 2 :(得分:-1)

你的代码没有输出任何东西的原因是因为它停留在那个getline循环中。

假设c ++ 11:

int main(){
  string line;
  cout <<"Please Enter a line"<< endl;
  getline(cin, line);
  line.erase(std::remove_if(line.begin(),  line.end(),  
               [](char ch) { return ispunct(ch) ? true : false; }), line.end());
  cout << line << endl;
  return 0;
}

int main(){
  string line;
  cout <<"Please Enter a line"<< endl;
  transform(line.begin(), line.end(), line.begin(), 
              [](char ch) {  return ispunct(ch) ? '\0' : ch; });
  cout << line << endl;
  return 0;
}