使用 C++ 迭代字符串中单词的最优雅方式
没有一种优雅的方式来迭代 C/C++ 字符串中的单词,对一些人来说最易读的方式可能是最优雅的,而对另一些人来说可能是最高效的。我列出了你可以用来实现这一点的 2 种方法。第一种方法是使用 stringstream 来读取以空格分隔的单词。这有点局限,但如果你提供适当的检查,它可以很好地完成这个任务。例如,>
示例代码
#include <iostream>
#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);
}
for(int i = 0; i<words.size(); i++)
cout << words[i] << endl;
}输出
Hello from the dark side
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP