C_C++

(C언어) 중복되지 않은 단어의 개수 세는 프로그램

고니자니 2024. 1. 23. 17:20
반응형

입력된 문장에서 중복을 제외한 단어의 개수를 세는 파이썬 프로그램입니다.
파이썬으로 작성된 코드는 맨 아래에 링크되어 있습니다.

 

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

int main() {
    // 문자열을 입력으로 받습니다.
    char input_string[1000];
    printf("문자열을 입력하세요:\n");
    fgets(input_string, sizeof(input_string), stdin);

    // 개행 문자를 제거하여 문자열을 정리합니다.
    input_string[strcspn(input_string, "\n")] = '\0';

    // 입력된 문자열을 공백을 기준으로 나눕니다.
    char* token = strtok(input_string, " ");
    char words[100][100];
    int word_count = 0;

    // 중복을 제거하기 위해 배열을 사용합니다.
    while (token != NULL) {
        // 중복되지 않은 단어인 경우에만 추가합니다.
        int is_duplicate = 0;
        for (int i = 0; i < word_count; i++) {
            if (strcmp(words[i], token) == 0) {
                is_duplicate = 1;
                break;
            }
        }

        if (!is_duplicate) {
            strcpy(words[word_count], token);
            word_count++;
        }

        token = strtok(NULL, " ");
    }

    // 중복되지 않은 단어의 개수를 출력합니다.
    printf("중복되지 않은 단어의 개수: %d\n", word_count);

    return 0;
}

 

입력 문자열:

C language is a powerful programming language. Python is also easy to learn.

(C언어) 중복되지 않은 단어의 개수 세는 프로그램

 

 


파이썬 코드:

https://coding-abc.tistory.com/269

 

(파이썬) 중복되지 않은 단어의 개수 세는 프로그램

입력된 문장에서 중복을 제외한 단어의 개수를 세는 파이썬 프로그램입니다. 문장을 split 함수로 공백을 기준으로 단어를 분리합니다. set 함수는 단어를 중복되지 않도록 해줍니다. 참고: split :

coding-abc.kr

 

728x90
반응형