闽公网安备 35020302035485号
适用场景:小规模数据,追求代码简单时。
适用场景:中等规模数据,想自己掌控逻辑时。
适用场景:现代项目,小数据量处理。
适用场景:大型项目,已经用Boost时。
适用场景:追求极致性能,愿意接纳Google生态时。
适用场景:特殊需求,或性能要求极高时。
2023-10-01|INFO|User login|user123 2023-10-02|ERROR|Server crash|system 2023-10-03|DEBUG|Processing data|user456目标是把每行按|分割,提取日期、日志级别、消息和用户ID。我们用3种方法(std::istringstream、std::string::find和自定义函数)来实现,带你体验不同方法的实战感觉。
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
std::vector<std::string> split(const std::string& s, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(s);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
std::stringlog = "2023-10-01|INFO|User login|user123";
std::vector<std::string> fields = split(log, '|');
std::cout << "日期: " << fields[0] << "\n";
std::cout << "级别: " << fields[1] << "\n";
std::cout << "消息: " << fields[2] << "\n";
std::cout << "用户: " << fields[3] << "\n";
return0;
}
过程讲解:评价:代码简洁,适合快速上手,但大数据量会慢。
#include <iostream>
#include <vector>
#include <string>
std::vector<std::string> split(const std::string& s, char delimiter) {
std::vector<std::string> tokens;
size_t start = 0;
size_t end = s.find(delimiter);
while (end != std::string::npos) {
tokens.push_back(s.substr(start, end - start));
start = end + 1;
end = s.find(delimiter, start);
}
tokens.push_back(s.substr(start)); // 最后一段
return tokens;
}
int main() {
std::stringlog = "2023-10-01|INFO|User login|user123";
std::vector<std::string> fields = split(log, '|');
std::cout << "日期: " << fields[0] << "\n";
std::cout << "级别: " << fields[1] << "\n";
std::cout << "消息: " << fields[2] << "\n";
std::cout << "用户: " << fields[3] << "\n";
return0;
}
过程讲解:评价:性能比方法1好,但得小心边界处理。
#include <iostream>
#include <vector>
#include <string>
std::vector<std::string> split(const std::string& s, char delimiter) {
std::vector<std::string> tokens;
std::string token;
for (char c : s) {
if (c == delimiter) {
if (!token.empty()) {
tokens.push_back(token);
token.clear();
}
} else {
token += c;
}
}
if (!token.empty()) {
tokens.push_back(token); // 最后一段
}
return tokens;
}
int main() {
std::stringlog = "2023-10-01|INFO|User login|user123";
std::vector<std::string> fields = split(log, '|');
std::cout << "日期: " << fields[0] << "\n";
std::cout << "级别: " << fields[1] << "\n";
std::cout << "消息: " << fields[2] << "\n";
std::cout << "用户: " << fields[3] << "\n";
return0;
}
过程讲解:4.简单直接,完全自己掌控。
评价:灵活性高,优化空间大,但得自己保证逻辑无误。
结论:小数据量差别不大,大数据量时自定义函数和find更占优势。