split()
string
형 데이터를 어떤 기호를 기준으로 두고 잘라야 할 때가 있다.
Python
, Java
, JavaScript
모두 가지고 있는 함수인데 c++
엔 없다.
a.split(",");
와 같이 사용되는데 구현하는 방법은 여러가지다.
이 글에서는 아래 두 함수를 조합하여 구현해보자.
substr()
string
을 인덱스 기반으로 잘라주는 도구다.
인자 하나만 쓰면 해당 인자부터 끝까지 잘라주고,
인자가 두개면 첫 번째 인자부터 두 번째 인자 길이만큼 떼어준다.
str.substr(0)
= str[0] ~ str[str.length()]
str.substr(3, 5)
= str[3] ~ str[3+5-1]
find()
string
에서 원하는 문자를 찾을 때 사용한다.
인자가 하나면 string
에서 해당 문자가 처음 등장하는 인덱스를 뱉고
인자가 두개면 첫 번째 인자(문자)를 두 번째 인자(탐색 시작 인덱스)부터 탐색한다.
만약 찾는 문자가 없으면 no position
이라는 의미의 string::npos
를 뱉는다.
split
구현하기#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
string str;
cin >> str; // 10-20+15+25-30
vector<string> v;
int prev = 0;
int curr = str.find('-');
while (curr != string::npos) {
string tmp = str.substr(prev, curr - prev);
v.push_back(tmp);
prev = curr + 1;
curr = str.find('-', prev);
}
v.push_back(str.substr(prev));
for (int i = 0; i < v.size(); i++) {
cout << v[i] << "\n";
}
/*
10
20+15+25
30
*/
}