[c++] 문자열에서 특정 패턴의 개수 세는 방법

C++에서는 문자열에서 특정 패턴의 개수를 셀 수 있는 여러 가지 방법이 있습니다.

1. 반복문을 이용한 방법

#include <iostream>
#include <string>

int countPattern(std::string str, std::string pattern) {
    int count = 0;
    for (size_t i = 0; (i = str.find(pattern, i)) != std::string::npos;) {
        i += pattern.length();
        count++;
    }
    return count;
}

int main() {
    std::string text = "ababababab";
    std::string pattern = "ab";
    int result = countPattern(text, pattern);
    std::cout << "패턴 " << pattern << "의 개수: " << result << std::endl;
    return 0;
}

2. 정규 표현식을 이용한 방법

정규 표현식을 사용하여 문자열에서 특정 패턴을 찾고 개수를 세는 방법도 있습니다. 이를 위해 std::regex 라이브러리를 사용할 수 있습니다.

#include <iostream>
#include <string>
#include <regex>

int countPatternUsingRegex(std::string str, std::string pattern) {
    std::regex reg(pattern);
    auto words_begin = std::sregex_iterator(str.begin(), str.end(), reg);
    auto words_end = std::sregex_iterator();
    return std::distance(words_begin, words_end);
}

int main() {
    std::string text = "ababababab";
    std::string pattern = "ab";
    int result = countPatternUsingRegex(text, pattern);
    std::cout << "패턴 " << pattern << "의 개수: " << result << std::endl;
    return 0;
}

3. Boost 라이브러리 사용

Boost 라이브러리에서는 boost::algorithm::count 함수를 사용하여 문자열에서 특정 패턴의 개수를 세는 방법이 있습니다.

#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>

int main() {
    std::string text = "ababababab";
    std::string pattern = "ab";
    int result = boost::algorithm::count(text, pattern);
    std::cout << "패턴 " << pattern << "의 개수: " << result << std::endl;
    return 0;
}

요약

C++에서는 문자열에서 특정 패턴의 개수를 세는 다양한 방법이 있습니다. 반복문, 정규 표현식, Boost 라이브러리를 활용하여 필요에 맞는 방법을 선택할 수 있습니다.

참고 문헌: