【发布时间】: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<<endl << "list of ...只有在输入字符串的第一个字符是空格时才被执行 - 我不认为你打算这样做,对吧? -
是的,我会在声明之前将其移动。谢谢!
标签: c++ string stringstream getline punctuation