结合find()和substr()实现字符串分割
*size_type find( const char str, size_type index, size_type length );
find()函数返回str在字符串中第一次出现的位置下标(从index开始查找,长度为length),如果没找到就返回string::npos。
#include<bits/stdc++.h>
using namespace std;
int main() {
string s = "123,456,789";
size_t pos = s.find(','); // 3
return 0;
}
basic_string substr( size_type index, size_type num = npos );
substr()函数返回本字符串的一个子串,从index开始,长num个字符。如果num没有指定,将是默认值 string::npos。这样,substr()函数将简单的返回从index开始的剩余的字符串。
例:
#include<bits/stdc++.h>
using namespace std;
int main() {
string s = "123,456,789";
size_t pos = s.find(','); // 3
string p = s.substr(0, pos); // 123
string q = s.substr(pos + 1); // 456,789
return 0;
}