C++IO流字符串拆分方法
C++的 IO 流字符串拆分方法挺多,最常用的组合就是 std::stringstream
搭配 std::getline
,写起来不复杂,效率也还不错。你要是按行读文件,直接上 getline
就行,省事儿。对付自定义分隔符的字符串,比如逗号、分号之类的,也有好几种写法,看着选就行。
标准库的 std::getline
是行级读取利器,文件时方便:
#include
#include
std::ifstream file("input.txt");
std::string line;
while (std::getline(file, line)) {
// 每一行的逻辑
}
如果你要拆成更细的片段,比如按逗号分割,可以用 std::stringstream
,方法也经典:
#include
#include
#include
std::string str = "one,two,three";
std::stringstream ss(str);
std::string token;
std::vector tokens;
while (std::getline(ss, token, ',')) {
tokens.push_back(token);
}
手写拆分也行,直接用 find
和 substr
组合,比较适合分隔符比较复杂或结构不规则的情况:
std::string str = "one;two;three";
std::vector tokens;
std::string token;
size_t pos = 0;
while ((pos = str.find(';')) != std::string::npos) {
token = str.substr(0, pos);
tokens.push_back(token);
str.erase(0, pos + 1);
}
tokens.push_back(str);
还有一种比较精致的做法,用 std::istringstream
搭配 istream_iterator
,挺适合空格分隔的词组,比如一句话:
#include
#include
#include
#include
std::string str = "one two three";
std::istringstream iss(str);
std::vector tokens(std::istream_iterator(iss), {});
如果你在搞 MFC,也可以用 CString
的 Find
和 Mid
来拆,逻辑跟上面类似,风格更偏 Windows 系:
#include
CString str = _T("one,two,three");
int pos = 0;
CString token;
while ((pos = str.Find(_T(','))) != -1) {
token = str.Mid(0, pos);
// token
str = str.Mid(pos + 1);
}
// 剩余的一段
token = str;
如果你经常和字符串打交道,建议这几种方式都试一下,哪种顺手用哪种,省事儿。
1.84MB
文件大小:
评论区