【问题标题】:How to use nested getline() function to get ride of special characters and punctuation in a string?如何使用嵌套的 getline() 函数来处理字符串中的特殊字符和标点符号?
【发布时间】:2012-09-05 05:00:27
【问题描述】:

我正在使用 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;
}
#############################输出

输入一句话:什么?当我说:“妮可,把我的拖鞋给我,给我 y night-cap,”是散文吗?

散文中的单词列表

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

按任意键继续。 . .

【问题讨论】:

  • "问题是它变得很长,而且我认为它不是很有效。"我是否正确理解您只是在问如何提高性能?除非它真的运行得很慢,否则为什么还要关心呢?你测量过性能吗?
  • 不是在性能方面,而是在额外(并且可能是不必要的)代码行方面。
  • 顺便说一句,我对您的 if (y=' ') 声明有意见。唯一能做的是下一行,cout&lt;&lt;endl &lt;&lt; "list of ... 只有在输入字符串的第一个字符是空格时才被执行 - 我不认为你打算这样做,对吧?
  • 是的,我会在声明之前将其移动。谢谢!

标签: c++ string stringstream getline punctuation


【解决方案1】:

使用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)。

【讨论】:

  • 您可能会注意到这是 C++11 代码。我认为并不是每个人都已经使用了兼容的编译器;)
  • 哦,您当前的代码还将删除破折号 (-) 和引号 (") - 这似乎不是 OP 想要的!
  • @nyarlathotep,只需定义一个谓词而不是 lambda。
  • @nyarlathotep,代码是如何做到这一点的示例。 OP 可以轻松地将其更改为他的确切需求。但是:它除了 a-z(或 A-Z)之外没有任何其他字符。 这似乎不需要 -"
  • 对,现在例子和描述似乎相互矛盾(或者代码还不完整)
猜你喜欢
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
  • 2016-02-20
  • 2013-12-19
  • 2017-08-22
  • 1970-01-01
  • 1970-01-01
  • 2014-03-22
相关资源
最近更新 更多