C++에서 문자열을 간단히 나누는 방법을 알아보겠따.
먼저 strtok 를 사용하여 char형 문자를 나누는 방법이다.
사용을위해 strtok 사용을위해 해더파일을 추가해준다.
#include<string.h>
다음 char 문자열을 하나 만들어 봅니다.
char str1[] = "a b c d e f";
해당 문자열을 공백을 기준으로 나누고 싶기때문에 strtok 에 공백을 넣어 줍니다.
char* tok1 = strtok(str1," ");
str1을 공백으로 나눈다. 나누어 졌는지 출력해보겠다.
while(tok1!=NULL){
cout<<tok1<<endl;
tok1 = strtok(NULL," ");
}
a
b
c
d
e
f
이런식으로 출력이 된다.
공백이아니라 문자도 마찬가지이다.
char str2[] = "가,나,다,라,마,바";
,(콤마) 로 구분된 문자역시 strtok 에 , 를 넣어주면 , 를 구분하여 나누어준다.
char* tok2 = strtok(str2,",");
while(tok2!=NULL){
cout<<tok2<<endl;
tok2 = strtok(NULL,",");
}
가
나
다
라
마
바
특이사항으로 여러개의 구분자로 구성되어있는 문자열도 나눌 수 있다.
char str3[] = "1,2-3;4 5";
이와같이 , - ; 공백 처럼 네가지 문자로 구분이 되어있는경우 모든 문자를 넣어주면 구분하여준다.
char* tok3 = strtok(str3,",-; ");
while(tok3!=NULL){
cout<<tok3<<endl;
tok3 = strtok(NULL,",-; ");
}
1
2
3
4
5
C++ 에서 간단히 문자를 나누는 방법을 알아보았습니다.
전체소스
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<string.h> | |
using namespace std; | |
int main() | |
{ | |
char str1[] = "a b c d e f"; | |
char str2[] = "가,나,다,라,마,바"; | |
char str3[] = "1,2-3;4 5"; | |
char* tok1 = strtok(str1," "); | |
while(tok1!=NULL){ | |
cout<<tok1<<endl; | |
tok1 = strtok(NULL," "); | |
} | |
char* tok2 = strtok(str2,","); | |
while(tok2!=NULL){ | |
cout<<tok2<<endl; | |
tok2 = strtok(NULL,","); | |
} | |
char* tok3 = strtok(str3,",-; "); | |
while(tok3!=NULL){ | |
cout<<tok3<<endl; | |
tok3 = strtok(NULL,",-; "); | |
} | |
} |