C언어 기초: 문자열 예제 (3): 토큰

김영채 (Kevin)·2020년 4월 26일
0

C언어

목록 보기
22/23
post-thumbnail

다음 문자열 예제다.

위가 input, 아래가 output이다. 위와 같이 문자열을 3개 입력을 우선 차례대로 받는다. 문자열 3개를 입력 받은 후에, 몇 개의 단어가 입력되었는지 계산하고, 문장에서 가장 긴 단어를 출력해야 한다. 가장 긴 단어가 여러 개 있다면, 가장 먼저 나온 단어를 출력하면 된다.

단어가 몇 개 있는지 알아야 하니, 문자열 예제(2)에서 살펴본 것처럼 delimiter 변수를 사용하고, count변수를 선언해야함을 알 수 있다.

또한, 가장 긴 단어를 알아내야 하기 때문에, strlen()함수도 분명 사용해야 할 것이다.

그리고 각 줄에서 어떤 단어가 제일 길 때, 임시로 다른 배열에다가 넣는 것이 좋아 strcpy() 함수를 사용해 배열에다가 임시로 넣는 기능을 수행해야 할 것이다.

대강 위와 같이 생각은 했는데, 막상 코드를 짜려니까 너무 헷갈렸다.

(처음에 뻘짓한 흔적)

단어를 구분할 때 쓸 delimiter 변수가 필요하니, delimiter 변수는 char *delimiter = " .,!\t\n"; 으로 설정하였다.

그리고, 문자열을 어차피 3개만 입력 받으니, while i<3 로 반복문을 설정하면 된다.

그리고 한 줄의 가장 긴 단어를 임의로 설정하기 위해서 lineMax 변수도 설정하였다.

 if (lineNum == 0)
 {
      strcpy(max, ptoken);
 }   

첫 번째 행 (lineNum==0) 이 돌 때 max 배열에 가장 처음 추출한 단어를 임의로 넣어둔다. 변수에 초기값을 주는 것이랑 비슷한 개념이다.

그 다음에, strcpy(lineMax, ptoken); 문장을 통해서 각 행에서 가장 긴 단어를 초기화한다.

이후에는,

if (strlen(lineMax) < strlen(ptoken))
      {
        strcpy(lineMax, ptoken);
      }
      ptoken = strtok(NULL, delimiter);
      count++;

위 코드를 이용해 매 행에서 가장 긴단어가 무엇인지 추출해내어, 찾아낸다면, lineMax에 넣는다. 그 와중에 count++;을 통해 몇 개의 단어가 있는지 세는 것도 잊지 말아야 한다.

그리고는,

if (strlen(max) < strlen(lineMax))
    {
      strcpy(max, lineMax);
    }

위 코드를 통해 3줄 중에서 가장 긴 단어가 무엇인지 계산하면 된다.

그럼 최종 코드를 보자:

int main()
{
  char input[255];
  char *delimiter = " .,!\t\n";
  char *ptoken;
  int count=0;
    
  int lineNum = 0;  // Line number
  char max[28];     // String with the total max length
  char lineMax[28]; // String with the max length of a line

  // Read 3 lines
  while (lineNum < 3)
  {
    gets(input);

    fseek(stdin, 0, SEEK_END); // flush the buffer

    ptoken = strtok(input, delimiter);
    

    // Initialize max length in first line
    if (lineNum == 0)
    {
      strcpy(max, ptoken);
    }

    // Initialize max length in the current line
    strcpy(lineMax, ptoken);

    while (ptoken != NULL)
    {
      // Get the token with the max length in the line
      if (strlen(lineMax) < strlen(ptoken))
      {
        strcpy(lineMax, ptoken);
      }
      ptoken = strtok(NULL, delimiter);
      count++;
    }

    // Get the string with total max
    if (strlen(max) < strlen(lineMax))
    {
      strcpy(max, lineMax);
    }

    lineNum++;
  }

  // Print out the string with the total max
  printf("%d %s\n", count, max);
}
profile
맛있는 iOS 프로그래밍

0개의 댓글