C++分割字符串
作者:互联网
给定一个字符串和分界符,将分割后的字符串存放在数组中。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
auto split = [](const string& s, char delim)-> vector<string>{
vector<string> ans;
string cur;
for(char ch : s){
if(ch == delim){
if(!cur.empty()){
ans.push_back(move(cur));
cur.clear();
}
}else{
cur += ch;
}
}
if(!cur.empty()){
ans.push_back(move(cur));
}
return ans;
};
// 测试用例1
//string str = "/a/./b/../..//c/";
//char delim = '/';
// 测试用例2
//string str = "/a/./b/../../c/";
//char delim = '/';
// 测试用例3
//string str = "I love you";
//char delim = ' ';
// 测试用例4
string str = "I love you";
char delim = ' ';
vector<string> res = split(str, delim);// 注意,连续出现相同的定界符视为一次分割
// 打印结果
cout << "res size = " << res.size() << endl;
for(string &name : res){
cout << name << endl;
}
return 0;
}
标签:分割,cur,delim,C++,char,str,ans,字符串,string 来源: https://blog.csdn.net/Dream_ping/article/details/122336611