[c++] 문자열에서 중복 단어 제거

우선, 문자열을 공백을 기준으로 단어로 분할해야 합니다. 그 다음에는 각 단어를 저장하면서 이미 나온 단어인지를 확인해야 합니다. C++의 unordered_set을 사용하여 이 작업을 수행할 수 있습니다.

다음은 중복된 단어를 제거하는 간단한 예제 코드입니다.

#include <iostream>
#include <string>
#include <sstream>
#include <unordered_set>

int main() {
    std::string input = "apple banana apple orange banana";
    std::istringstream iss(input);
    std::unordered_set<std::string> wordSet;
    
    std::string word;
    while (iss >> word) {
        if (wordSet.insert(word).second) {
            std::cout << word << " ";
        }
    }

    return 0;
}

이 예제에서는 input 문자열을 공백을 기준으로 단어별로 읽어들인 후, wordSet에 삽입합니다. 만약 단어가 이미 존재한다면 삽입되지 않으며, 존재하지 않는 단어만 출력됩니다.

이 코드는 “apple banana orange”를 출력할 것입니다.

이 방법을 사용하여 단어를 중복 없이만 출력하는 코드를 작성할 수 있습니다.

참고문헌: