c++ 문자열을 구분자로 분리하기
string class만 사용해서 구분자로 문자열 분리하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <vector>
#include <string>
using namespace std;
vector<string> split(string input, string delimiter)
{
vector<string> vec;
int pos = 0;
string token = "";
while ((pos = input.find(delimiter)) != string::npos)
{
token = input.substr(0, pos);
vec.push_back(token);
input.erase(0, pos + delimiter.length());
}
vec.push_back(input);
return vec;
}
string stream을 사용해서 구분자로 문자열 분리하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <vector>
#include <string>
#include <sstream>
using namespace std;
vector<string> split(const string& str, char delimiter)
{
vector<string> vec;
string token;
stringstream ss(str);
while (getline(ss, token, delimiter))
{
vec.push_back(token);
}
return vec;
}
This post is licensed under CC BY 4.0 by the author.