遍历 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);
}
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP