How do I iterate over the words of a string?(如何迭代字符串的单词?)
问题描述
我正在尝试遍历字符串中的单词.
I'm trying to iterate over the words of a string.
可以假设字符串由空格分隔的单词组成.
The string can be assumed to be composed of words separated by whitespace.
请注意,我对 C 字符串函数或那种字符操作/访问不感兴趣.另外,请在您的回答中优先考虑优雅而不是效率.
Note that I'm not interested in C string functions or that kind of character manipulation/access. Also, please give precedence to elegance over efficiency in your answer.
我现在最好的解决方案是:
The best solution I have right now is:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string s = "Somewhere down the road";
istringstream iss(s);
do
{
string subs;
iss >> subs;
cout << "Substring: " << subs << endl;
} while (iss);
}
有没有更优雅的方法来做到这一点?
Is there a more elegant way to do this?
推荐答案
值得一提的是,这是另一种从输入字符串中提取标记的方法,它仅依赖于标准库工具.这是 STL 设计背后的力量和优雅的一个例子.
For what it's worth, here's another way to extract tokens from an input string, relying only on standard library facilities. It's an example of the power and elegance behind the design of the STL.
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
int main() {
using namespace std;
string sentence = "And I feel fine...";
istringstream iss(sentence);
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
ostream_iterator<string>(cout, "
"));
}
可以使用相同的通用 复制算法.
Instead of copying the extracted tokens to an output stream, one could insert them into a container, using the same generic copy algorithm.
vector<string> tokens;
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter(tokens));
...或者直接创建vector:
vector<string> tokens{istream_iterator<string>{iss},
istream_iterator<string>{}};
这篇关于如何迭代字符串的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何迭代字符串的单词?
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
