题目描述
字符串切割(raw:adbacaf sep:bac result就是ad和af)
算法分析
涉及到string类的两个函数find和substr:
1、find函数
原型:size_t find ( const string& str, size_t pos = 0 ) const;
功能:查找子字符串第一次出现的位置。
参数说明:str为子字符串,pos为初始查找位置。
返回值:找到的话返回第一次出现的位置,否则返回string::npos2、substr函数
原型:string substr ( size_t pos = 0, size_t n = npos ) const;
功能:获得子字符串。
参数说明:pos为起始位置(默认为0),n为结束位置(默认为npos)
返回值:子字符串
提交代码:
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
int main()
{
string raw, sep;
cin >> raw >> sep;
string temp;
vector<string> ans;
string str = raw + sep;
size_t pos = str.find(sep);
size_t length = str.size();
while (pos != string::npos) {
string x = str.substr(0, pos);
ans.push_back(x);
str = str.substr(pos + sep.size());
pos = str.find(sep);
}
for (string each : ans)
cout << each << endl;
return 0;
}