迭代C/C++字符串单词的最优雅方法
没有一种优雅的方式用于迭代C/C++字符串的单词。对于某些人来说,最具可读性也最优雅,而对于另一些人来说,最具性能则最优雅。我已经列出了2种可以用来实现此目的的方法。第一种方法是使用stringstream读取用空格分隔的单词。这种方法有些限制,但如果你执行适当的检查,也能很好地完成这项任务。
示例
#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) { // Provide proper checks here for tmp like if empty // Also strip down symbols like !, ., ?, etc. // Finally push it. 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)) { // Provide proper checks here for tmp like if empty // Also strip down symbols like !, ., ?, etc. // Finally push it. words.push_back(tmp); } }
广告