使用 C++ 迭代字符串单词的最优雅方法
没有一种优雅的方法可以迭代C/C++字符串的单词。最易读的方式对某些人来说是最优雅的,而对其他人来说是最高效的。我列出了2种可用于实现此目的的方法。第一种方法是使用字符串流来读取由空格分隔的单词。这有点有限,但如果您提供适当的检查,则可以很好地完成任务。例如,>
示例代码
#include#include #include #include using namespace std; int main() { string str("Hello from the dark side"); string tmp; //在每次迭代中存储单词的字符串。 stringstream str_strm(str); vector words; //创建向量来保存我们的话 while (str_strm >> tmp) { //在此处为tmp提供适当的检查,如为空 //还要去掉像!,.,?等符号。 //最后推一下。 words.push_back(tmp); } for(int i = 0; i 输出结果 Hello from the dark side