strtok 함수 구현 방법이다.
/* https://coding-factory.tistory.com/592 */
// #define NULL ((void*)0)
#include <stdio.h>
char* strtok1(char* str, const char* delimiters ){
static char* pCurrent;
char* pDelimit;
if ( str != NULL ) pCurrent = str;
else str = pCurrent;
if(*pCurrent == NULL) return NULL;
while (*pCurrent) { /* 문자열 점검 */
pDelimit = (char*)delimiters ;
while (*pDelimit){
if(*pCurrent == *pDelimit){
*pCurrent = NULL;
++pCurrent;
return str;
}
++pDelimit;
}
++pCurrent;
}
return str; /* 더이상 자를 수 없다면 NULL반환 */
}
/* https://hand-over.tistory.com/29 */
char *strcpy1(char *dest, const char *src) {
char *tmp = dest;
/*
* src 가 null byte 일때까지 dest에 한자씩 복사한 후 리턴합니다.
*/
while ((*dest++ = *src++) != '\0')
/* nothing */;
return tmp;
}
char *nth(char *str, char *ans, int cnt) {
int i;
char *p;
char str2[1024];
strcpy1(str2, str);
for( i = 1, p= strtok1(str2, "-"); p!=NULL; p=strtok1(NULL, "-"), i++) {
if( i == cnt ) { strcpy1(ans, p); return ans; }
}
return NULL;
}
int main( ) {
char str1[]="110-223-356-489-514-659";
char *p;
char ans[128];
for( int i = 1; i < 7; i++) {
p = nth(str1, ans, i);
puts(p);
}
return 0;
}
실행결과는 아래와 같다.

'C 언어' 카테고리의 다른 글
| Basic interpreters (1) | 2022.06.05 |
|---|---|
| C언어 getString 함수 만들기 (0) | 2022.06.01 |
| C언어 2차원 문자열 어레이 동적 생성 (0) | 2021.12.19 |
| C언어 getline 함수(개행문자 제외) (0) | 2021.12.04 |
| C 언어 substring 함수 구현 방법 (1) | 2021.11.23 |
댓글