static const size_t npos = -1;
用来标识不存在的位置
npos
是一个常数,表示size_t
的最大值(Maximum value for size_t
)。许多容器都提供这个东西,用来表示不存在的位置,类型一般是std::container_type::size_type
。find()
寻找首个等于给定字符序列的子串。搜索始于pos
,即找到的子串必须不始于pos
之前的位置。
#include <string.h>
#include <cstring>
#include <iostream>
#include <list>
#include <vector>
using namespace std;
void splitStr(std::string src, std::string pattern,
std::vector<std::string> &sList) {
int pos2 = 0;
cout << "src " << src << endl;
for (int i = 0; i < src.size();) {
pos2 = src.find('\n', i);
cout << "pos2 " << pos2;
if (pos2 != std::string::npos) {
std::string strT = src.substr(i, pos2 - i);
cout << " strT " << strT << endl;
sList.push_back(strT);
i = pos2 + 1;
continue;
} else {
sList.push_back(src.substr(i, src.size() - 1));
}
break;
}
}
int main() {
string str = "\n10000\n20000";
string pattern = "\n";
std::vector<std::string> sList;
splitStr(str, pattern, sList);
cout << "\nsize " << sList.size() << endl;
for (int i = 0; i < sList.size(); i++) {
cout << "content " << sList.at(i) << endl;
}
return 0;
}
输出结果
src
10000
20000
pos2 0 strT
pos2 6 strT 10000
pos2 -1
size 3
content
content 10000
content 20000