[c++] 문자열에서 특정 문자열의 출현 횟수 계산

C++에서는 문자열에서 특정 부분 문자열이 출현하는 횟수를 계산하는 여러 가지 방법이 있습니다. 하나의 방법은 간단하게 문자열을 반복해서 탐색하면서 매칭되는 부분 문자열을 세는 것입니다.

방법 1: 루프를 이용한 계산

아래의 C++ 코드는 이러한 방법을 사용하여 부분 문자열의 출현 횟수를 계산하는 예시입니다:

#include <iostream>
#include <string>

int countSubstring(const std::string& str, const std::string& sub)
{
    if (sub.length() == 0) return 0;
    int count = 0;
    for (size_t offset = str.find(sub); offset != std::string::npos; 
         offset = str.find(sub, offset + sub.length()))
    {
        ++count;
    }
    return count;
}

int main()
{
    std::string str = "hellohellohelloworldhello";
    std::string sub = "hello";
    int occurrences = countSubstring(str, sub);
    std::cout << "Occurrences: " << occurrences << std::endl;
    return 0;
}

방법 2: 정규표현식 사용

또 다른 방법은 C++의 정규표현식 라이브러리를 사용하여 부분 문자열을 찾는 것입니다. 이를 통해 더 복잡한 매칭 패턴을 처리할 수 있습니다.

#include <iostream>
#include <regex>

int countSubstring(const std::string& str, const std::string& sub)
{
    std::regex rx(sub);
    auto words_begin = std::sregex_iterator(str.begin(), str.end(), rx);
    auto words_end = std::sregex_iterator();
    return std::distance(words_begin, words_end);
}

int main()
{
    std::string str = "hellohellohelloworldhello";
    std::string sub = "hello";
    int occurrences = countSubstring(str, sub);
    std::cout << "Occurrences: " << occurrences << std::endl;
    return 0;
}

위 코드는 C++에서 문자열에서 특정 부분 문자열의 출현 횟수를 계산하는 방법을 보여줍니다. 여기서는 루프를 사용하는 간단한 방법과 정규표현식을 사용하는 방법 두 가지를 살펴보았습니다.