如何使用嵌套的getline()函数来摆脱字符串中的特殊字符和标点符号?

时间:2012-09-12 08:03:54

标签: c++ string stringstream getline punctuation

我使用getline()函数来获取句子中的特殊字符和标点符号,这样当我显示句子中包含的单词时,它在a-z(或A-Z)旁边没有任何其他字符。问题是它变长了,我认为它不是真的有效。我想知道我能否以有效的方式做到这一点。我使用的是Dev-C ++,下面的代码是用C ++编写的。谢谢你的帮助。

#include <string>
#include <iostream>
#include <ctype.h>
#include <sstream>

using namespace std;



int main()
{
 int i=0;
 char y; 
 string prose, word, word1, word2;
 cout << "Enter a sentence: ";
 getline(cin, prose);

 string mot;
 stringstream ss(prose);


 y=prose[i++];
 if (y=' ')   // if character space is encoutered...


  cout<<endl << "list of words in the prose " << endl;
  cout << "---------------------------"<<endl;
  while(getline(ss, word, y))  //remove the space...
   {

      stringstream ss1(word);      

     while(getline(ss1, word1, ','))  //remove the comma...
       {

          stringstream ss2(word1);  //remove the period
          while(getline(ss2, word2, '.'))
           cout<< word2 <<endl; //and display just the word without space, comma or period.
       }
   }      


     cout<<'\n';
    system ("Pause");
    return 0;
}
#############################输出

输入一句话:什么?当我说:“妮可,把我的拖鞋带给我,然后给我 那个夜晚,“那是散文吗?

散文中的单词列表

什么? 什么时候 一世 说: “妮可 带来 我 我的 拖鞋 和 给 我 我的 睡帽 “ 是 那 散文?

按任意键继续。 。

1 个答案:

答案 0 :(得分:3)

使用std::remove_if()

std::string s(":;[{abcd 8239234");

s.erase(std::remove_if(s.begin(),
                       s.end(),
                       [](const char c) { return !isalpha(c); }),
        s.end());

如果您没有C ++ 11编译器,请定义谓词而不是使用lambda(在线演示http://ideone.com/NvhKq)。