개발자의 길

[C++] C++에서 string 문자열을 받아와 split 하기

토아드 2018. 9. 15. 23:45
반응형

C++로 알고리즘 문제를 풀다 보면 다른 언어에 비해 구현하기 불편한 부분이 은근 많다.


Java의 split 함수와 같이 작관적이고 쓰기 간편한 함수가 있었으면 좋겠지만, C++에서는 되게 다양한 방법으로 split을 할 수가 있어서 뭘 선택해야할지 꽤나 어려웠다.


그래서 정보를 여러곳에서 찾아보고, 괜찮은 방법을 몇가지 소개하고자 한다.


1. istringstream 과 getline 함수를 사용


 istringstream 은 sstream 을 include 하여 사용할수있는 스트림 클래스이다.

 

 사용법은 다음과 같다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
#include<string>
#include<sstream>>
#include<vector>
 
using namespace std;
 
int main()
{
    string as = "this,is,string";
    istringstream ss(as);
    string stringBuffer;
    while (getline(ss, stringBuffer, ','))
    {
        cout << stringBuffer << " ";
    }
 
    return 0;
}
cs


출력 결과 : this is string


2. string의 find 함수를 사용


 find 함수는 string 에서 주어진 문자열을 찾는 함수다. 순차적으로 구분문자를 바꿀 수 있으므로 구분문자가 두개 이상일 때 유용하게 사용할수 있을것 같다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<iostream>
#include<string>
#include<sstream>>
#include<vector>
 
using namespace std;
 
int main()
{
    string as = "this,is,string";
    size_t previous = 0, current;
    current = as.find(',');
    //find 함수는 해당 위치부터 문자열을 찾지 못할 경우 npos를 반환한다.
    while (current != string::npos)
    {
        // 첫 인자의 위치부터 두번째 인자 길이만큼 substring을 반환
        string substring = as.substr(previous, current - previous);
        cout << substring << " ";
        previous = current + 1;
        //previous 부터 ,이 나오는 위치를 찾는다.
        current = as.find(',',previous); 
    }
    //마지막 문자열 출력
    cout << as.substr(previous, current - previous);
    return 0;
}
cs


출력 결과 : this is string


참고

http://www.martinbroadhurst.com/how-to-split-a-string-in-c.html

https://stackoverflow.com/questions/236129/the-most-elegant-way-to-iterate-the-words-of-a-string

반응형