![](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FyqR7T%2FbtqMqB01TSA%2FB3QBNWpmRvHe497B6MXCm0%2Fimg.png)
C++ 문자열 나누기 - string split
Notepad96
·2020. 11. 3. 12:34
![](https://blog.kakaocdn.net/dn/yqR7T/btqMqB01TSA/B3QBNWpmRvHe497B6MXCm0/img.png)
1. split
Java, JavaScript, Python 등등 대부분의 언어에서 지원하는 문자열 함수이다.
split은 특정 문자를 기준으로 문자열을 나누어 준다.
ex) 문자열 "abc ef ghi" 을 " "로 나눈다하면
"abc", "ef", "ghi" 를 리턴해준다.
2. 코 드
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
using namespace std;
vector<string> split(string s, string divid) {
vector<string> v;
char* c = strtok((char*)s.c_str(), divid.c_str());
while (c) {
v.push_back(c);
c = strtok(NULL, divid.c_str());
}
return v;
}
vector<string> split2(string s, string divid) {
vector<string> v;
int start = 0;
int d = s.find(divid);
while (d != -1){
v.push_back(s.substr(start, d - start));
start = d + 1;
d = s.find(divid, start);
}
v.push_back(s.substr(start, d - start));
return v;
}
int main() {
string s = "ab,cdef gh-iklmn";
string s2 = "ab,cdef,gh,iklmn";
vector<string> v = split(s, ", -");
vector<string> v2 = split2(s2, ",");
cout << "문자열 1 : " << s << "\n";
for (string i : v) {
cout << i << "\n";
}
cout << "====================\n";
cout << "문자열 2 : " << s2 << "\n";
for (string i : v2) {
cout << i << "\n";
}
return 0;
}
![](https://blog.kakaocdn.net/dn/bnjYSS/btqMmoVXhiO/m6pXcb7OBRr7hsMn9o5pqk/img.png)
2-1. strtok() 사용
split 함수가 strtok()을 사용하여 문자열을 나눈다.
해당 방법의 좋은점은 문자열을 나눌 시 여러 구분자를 사용할 수 있다는 점이다.
첫번 째 문자열 s를 보면 "ab,cdef gh-iklmn" 처럼 문자열 내의 쉼표(,) 공백( ) 하이픈(-) 을 포함하고 있다.
이를 split 함수 호출 시 두번 째 인수로 구분자들의 문자열 전달하면 모든 구분자에 따라서 문자열을 나누어 준다.
2-2. find() & substr() 사용
int find( 찾을 문자열 [ ,찾기 시작할 인덱스]) : return 찾은 문자열 인덱스
string substr( 자르기 시작할 인덱스 [ ,길이]) : return 자른 문자열
3. 참 조
string - C++ Reference
www.cplusplus.com
strtok - C++ Reference
Splitting string "- This, a sample string." into tokens: This a sample string
www.cplusplus.com
'C++ > Algorithm' 카테고리의 다른 글
[Algorithm/C++] 버블 정렬(Bubble Sort) - 거품 정렬 (0) | 2022.09.18 |
---|---|
C++ 숫자 각 자릿수 구하기, 문자열 숫자 각 자릿수 구하기 (0) | 2020.11.21 |
C++ Integer to Binary - 2진수 구하기 (0) | 2020.11.19 |
C++ 소수 판별하기 (0) | 2020.11.16 |
2의 n제곱 수인지 판별하기 (0) | 2020.11.07 |