迭代C / C ++字符串中单词的最优雅方法
没有一种优雅的方法可以迭代C/C++字符串的单词。对于某些人来说,最易读的方式可以说是最优雅的,而对于另一些人来说,则可以说是性能最高的。我列出了两种可用于实现此目的的方法。第一种方法是使用字符串流读取以空格分隔的单词。这有一点限制,但是如果您提供适当的检查,则可以很好地完成任务。
示例
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main() {
string str("Hello from the dark side");
string tmp; // A string to store the word on each iteration.
stringstream str_strm(str);
vector<string> words; // Create vector to hold our words
while (str_strm >> tmp) {
//在此处为tmp提供适当的检查,例如是否为空
//同时剥离下来的符号一样,等!?
//最后推一下。
words.push_back(tmp);
}
}另一种方法是提供一个自定义定界符,以使用getline函数分割字符串-
示例
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main() {
std::stringstream str_strm("Hello from the dark side");
std::string tmp;
vector<string> words;
char delim = ' '; // Ddefine the delimiter to split by
while (std::getline(str_strm, tmp, delim)) {
//在此处为tmp提供适当的检查,例如是否为空
//同时剥离下来的符号一样,等!?
//最后推一下。
words.push_back(tmp);
}
}热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿