문제

임의의 문장을 입력받아 각 단어별로 나눈 후에 단어들의 중복되는 개수를 구하는 프로그램을 작성하시오.

 

<처리조건>
(1) 입력된 스트링은 글자의 제한은 없다. 즉 공백이나 ', ' 등도 입력으로 들어 올 수 있다.
(2) 입력된 문장에서 각 단어사이의 구분은 공백으로 한다.
(3) 단어에는 공백을 제외한 단어들만이 포함된다.

 

입력형식

임의의 문장을 입력받는다.(문장의 길이는 200 이하)

하나의 결과가 나온 후에도 계속 새로운 입력을 받다가, "END"가 입력되면 프로그램을 종료한다. (문장의 개수를 30을 넘지 않는다.)

 

출력형식

 

각 문장 단위로 단어들의 발생 빈도를 오름차순 크기(아스키코드)순으로 출력한다.

 

<코드>

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

typedef struct word{
	char name[100];
	int freq;
}WORD;

typedef struct words{
	int len;
	int capacity;
	WORD *data;
}WORDS;

int compare( const void *n1, const void *n2)
{
	return strcmp((const char *)n1, (const char *)n2);
}

void destroy_words(WORDS *list)
{
	free(list->data);
	list->len = 0;
	list->capacity = 0;

	free(list);
}	

void input(char *name, WORDS *list)
{
	int check = 0;
	
	for(int j=0; j<list->len; j++)
	{
		if(!strcmp(name, list->data[j].name))
		{
			check = 1;
			list -> data[j].freq++;
			break;
		}	
	}
	
	if(!check)
		{
		//full memory
		if(list->capacity == list->len)
		{
			list->data = (WORD*)realloc(list->data, list->capacity * 2 * sizeof(WORD));
			list->capacity *= 2;
		}
		
		strcpy(list->data[list->len].name, name);
		list->data[list->len++].freq = 1;
	}
}

int main()
{
	char arr[200];
	char *ptr;
	
	while(1)
	{
		scanf(" %[^\n]s", arr);
		
		if(!strcmp("END", arr))
			break;
		
		WORDS *list = (WORDS *)malloc(sizeof(WORDS));
	
		list->len = 0;
		list->capacity = 1;
		list->data = (WORD *)malloc(list->capacity*(sizeof(WORD)));
		
		ptr = strtok(arr, " ");

		while (ptr != NULL)
		{
			input(ptr, list);
			ptr = strtok(NULL, " ");
		}
		
		qsort(list->data, list->len, sizeof(WORD), compare);
	
		for(int i=0; i<list->len; i++)
		{
			printf("%s : %d\n", list->data[i].name, list->data[i].freq);
		}
	
		destroy_words(list);
	}
	
	
	
	return 0;
}

'코딩 > Beginner Coder' 카테고리의 다른 글

1880 : 암호풀기(Message Decowding)  (0) 2020.06.03
2857 : 세로읽기  (0) 2020.06.03
2514 : 문자열 찾기  (0) 2020.06.03
2604 : 그릇  (0) 2020.06.03
3106 : 진법 변환  (0) 2020.06.02

+ Recent posts