没有一种优雅的方法可以迭代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);
}
}