본문 바로가기
Regex

C++ split (string 인자 여러개로 나누기, C++도 regex를 이용하여 자바나 파이썬처럼 가능합니다)

by 콩순이냉장고 2021. 8. 23.

이글을 읽기전에 여러분들은 c++을 split에대해 찾았을 거라 생각합니다.

대체로 getline을 이용한것이 많지만 

regex_token_iterator<string::iterator>를 이용하여 가능합니다.

간략한것은 sregex_token_iterator()를 이용하는것이 코드를 줄이는것이고

 

우선 코드부터 보자면

1
2
3
4
5
6
7
#include <bits/stdc++.h>
using namespace std;
vector<string> split(string s, string pattern = " ") {
    regex re(pattern);
    sregex_token_iterator it(s.begin(), s.end(), re, -1), end;
    return vector<string>(it, end);
}
cs

이렇습니다. 매우 간단하죠? 더 줄일수 있지만 이해하기 편하도록 조금은 늘렸습니다.

그럼 사용법의 코드를 한번 보시죠

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//By 콩순이냉장고
#include <bits/stdc++.h>
using namespace std;
vector<string> split(string s, string pattern = " ") {
    regex re(pattern);
    sregex_token_iterator it(s.begin(), s.end(), re, -1), end;
    return vector<string>(it, end);
}
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    string s = "abc efgh..ijkl:mnopq.rstu.vwxyz";
    cout << "original string : " << s << endl;
    cout << "-------------------------------------------" << endl;
    //여러가지 인자로 나누기
    vector<string> v = split(s, R"((\.\.|\.| |,|:))");
    cout << "나눈 개수 : " << v.size() << endl;
    for (int i = 0; i < v.size(); i++) {
        cout << v[i] <<" "<<v[i].size()<< endl;
    }
}
 
 
cs

 

 

 

 

어때요? 매우신기하죠? c++도 split를 자바나 파이썬처럼 여러개 인자를 받거나 단순히 문자크기가 하나만 받아

getline으로 split를 하는 코드를 자주 썼었는데 regex를 공부하고나서 스스로 c++ 라이브러리 들을 공부하다보니 방법을 찾아 공유해봅니다. 

 

궁금한점 혹은 모르는점 어떤 질문이든 댓글은 언제나 환영입니다.

공감? 눌러주실꺼죠??

 

'Regex' 카테고리의 다른 글

regex 메타 문자 사용  (0) 2021.09.04
c++ regex 문자 집합(여러 문자 중 하나와 일치시키기)  (0) 2021.09.04
c++ regex 모든 문자 찾기  (2) 2021.08.31
c++ regex 문자 하나 찾기  (0) 2021.08.31