본문 바로가기

[C언어 무따기]strtok() 함수 정리

반응형
-기능-

문자열을 토큰(token) 단위로 나누어준다.
토큰(token)이란 특정한 구분자(delimiter)로 분리되는 문자열의 구성 요소를 말한다.
예를 들어 구분자가 "/"라면 "2009/10/01" 이라는 문자열의 토큰(token)은 2009, 10, 01 세 개가 된다. 
이 함수를 사용하면 공백 문자는 물론이고 원하는 문자로 전체 문자열 중에서 단어를 쪼갤 수 있다.


#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    int i,j;
    int count= 0;
    
    char str[5][50];    //2차원 배열 선언. 
    char *token;        //문자형 포인터 변수 선언. 
    
    strcpy(str[0], "the most important step in implementing DVFS is");
    strcpy(str[1], "prediction of the future workload, whicj allows");
    strcpy(str[2], "one to choose the minimum required voltage/frequency");
    strcpy(str[3], "levels while satisfying key constrints on energy");
    strcpy(str[4], "and QoS. As proposed in this paper, a somple interval-");
    
    for(i = 0; i < 5; i++)
    { 
          token = strtok(str[i], " ");   //공백문자를 사용하여 str[i]에 있는 문자열
                                         //중에서 단어 추출 
          
          while(token)
          {
                      count++;                    //추출한 단어인 token이 존재하는한 
                      printf("%s\n" , token);     //count하나 증가시킴.
                       
                      token = strtok(NULL , " "); //현재 위치의 공백 문자를 
                                                  //NULL로 바꾸고 문자열에서 그 다음 단어
                                                  //추출 
                      
          }
    }
    
    printf("단어의 개수 : %d\n", count);

  system("PAUSE");  
  return 0;
}

반응형
-->