C++ 中 “split” 函数的实现

刷题常见,以作备忘!!!

1、使用stringfind()函数和substr()函数实现:

1
2
3
4
5
6
7
8
9
10
11
12
vector<string> format_string(string &str, char &delim)
{
str += delim;
vector<string> res;
int start = 0, end = 0;
while((end = str.find(delim, start)) != str.npos)
{
res.emplace_back(str.substr(start, end - start));
start = end + 1;
}
return res;
}

2、使用stringstreamgetline()函数实现:

头文件:

1
2
3
#include <string>
#include <vector>
#include <sstream>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
vector<string> format_string(const string& str, const char delim)
{
string str_t = str + delim;
vector<string> res;
stringstream sstream(str_t);
string sub_str = "";
while(getline(sstream, sub_str, delim))
{
if(!sub_str.empty())
{
res.emplace_back(sub_str);
}
}
return res;
}
Author: wnxy
Link: https://wnxy.xyz/2022/07/26/cpp_format_string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.