【C++】文字列内の単語の出現回数をカウントする方法

【C++】文字列内の単語の出現回数をカウントする方法

基本的な方法

まず、単語を分割する基本的な方法を紹介します。C++では、istringstream を使うことで、簡単に文字列を単語ごとに分割できます。

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

int main() {
    std::string text = "This is a sample text with some sample words.";
    std::istringstream iss(text);
    std::string word;

    while (iss >> word) {
        std::cout << word << std::endl;
    }
    return 0;
}

このプログラムを実行すると、スペースで区切られた単語が1行ずつ出力されます。

mapを使った方法

単語の出現回数をカウントするには、std::map を利用します。

#include <iostream>
#include <sstream>
#include <string>
#include <map>

int main() {
    std::string text = "this is a test this is only a test";
    std::istringstream iss(text);
    std::string word;
    std::map<std::string, int> word_count;

    while (iss >> word) {
        word_count[word]++;
    }

    for (const auto &pair : word_count) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
    return 0;
}

このプログラムを実行すると、各単語の出現回数が表示されます。

大文字小文字を無視する方法

大文字小文字を区別せずにカウントしたい場合、単語をすべて小文字に変換します。

#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <cctype>

std::string to_lower(std::string str) {
    for (char &c : str) {
        c = std::tolower(c);
    }
    return str;
}

int main() {
    std::string text = "This is a Test. This is only a test.";
    std::istringstream iss(text);
    std::string word;
    std::map<std::string, int> word_count;

    while (iss >> word) {
        word = to_lower(word);
        word_count[word]++;
    }

    for (const auto &pair : word_count) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
    return 0;
}

このプログラムでは、すべての単語を小文字に変換してからカウントします。

句読点を無視する方法

句読点を無視するためには、単語から記号を削除する処理を追加します。

#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <cctype>

std::string clean_word(std::string word) {
    std::string result;
    for (char c : word) {
        if (std::isalpha(c)) {
            result += std::tolower(c);
        }
    }
    return result;
}

int main() {
    std::string text = "Hello, world! This is a test. Hello again!";
    std::istringstream iss(text);
    std::string word;
    std::map<std::string, int> word_count;

    while (iss >> word) {
        word = clean_word(word);
        if (!word.empty()) {
            word_count[word]++;
        }
    }

    for (const auto &pair : word_count) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
    return 0;
}

このプログラムでは、英字のみを抽出し、すべて小文字に変換してカウントしています。

まとめ

  • 基本的な単語分割は istringstream を使う
  • 単語のカウントには std::map を使用
  • 大文字小文字を無視する場合は tolower を利用
  • 句読点を取り除くには isalpha を活用

この方法を組み合わせることで、より正確な単語の出現回数をカウントできます。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です