迭代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);
}
}热门推荐
10 广西考试祝福语结婚简短
11 猪年祝福语简短小孩
12 元旦祝福语送长辈简短
13 恭喜二宝祝福语简短
14 祝福语暖心话简短
15 国庆中秋祝福语简短兄弟
16 朋友订婚的祝福语简短
17 送弟弟中秋祝福语简短
18 爱生日祝福语简短独特