Recommanded Free YOUTUBE Lecture: <% selectedImage[1] %>

설명

산하님의 [wiki:토큰추출하기]를 조각코드 모음으로 옮겼습니다.

strsep이나 strtok 같은 토큰 추출 함수를 만들어본다. 기존의 표준함수들은 메모리를 할당하며 포인터를 반환하는데 이것이 언제 해제되는지 알 수 없다. (물론, glibc소스를 보면된다.) 소스는 보지 않았지만 대략, 사용자가 직접 해제해야 할 것 같아 보인다. 또한, 둘다 man을 보면 주의가 보인다. 그래서, 용도에 맞고 더 좋은(내가 보기에) 함수를 만들어 사용한다.

strsep의 NOTES :

The strsep() function was introduced as a replacement for strtok(), since the latter cannot handle empty fields. However, strtok() conforms to ANSI-C and hence is more portable.

strtok의 BUGS : Never use these functions. If you do, note that: These functions modify their first argument. These functions cannot be used on constant strings. The identity of the delimiting character is lost. The strtok() function uses a static buffer while parsing, so it's not thread safe. Use strtok_r() if this matters to you.

사용방법

char *token(char *str, char *src, const char* sep);
  1. str : 토큰 분리를 위한 원본 문자열
  2. src : 토큰 분리후 다음 문자열을 가르키는 포인터
  3. sep : 토큰
  4. return : 더이상 토큰이 없거나 '\0'을 만나면
#include "token.h"

int main() {
   char src[20];
   char str[20];
   char* next = &src[0];
   strcpy(src, "ab1de12eoqd12dq");
   while(next = token(str, next, "12")) {
      printf("%s\n", str);
   }
   return(0);
}

코드

#include <stdio.h>

char* token(char* str, char* src, const char* sep) {
   int i = 0;
   if (*src == '\0') return(NULL);
   while (1) {
      if (sep[i] == '\0') {
         str -= strlen(sep);
         break;
      } else if (*src == sep[i]) {
         i++;
      } else i = 0;
      if (*src == '\0') break;
      *str++ = *src++;
   }
   *str = '\0';
   return(src);
}

변경사항

2004/01/08