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

아래는 C++에서 문자열에서 특정 문자의 개수를 세는 예제 코드입니다.

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    char target = 'o';
    int count = 0;

    for (char c : str) {
        if (c == target) {
            count++;
        }
    }

    std::cout << "The number of '" << target << "' in the string is: " << count << std::endl;
    return 0;
}

위 예제 코드는 ‘o’가 문자열 “Hello, World!”에 나타나는 횟수를 세는 방법을 보여줍니다.

또 다른 방법으로는 std::count 알고리즘을 사용하는 것이 있습니다. std::count는 특정 값이 범위 내에서 나타나는 횟수를 세는 데 사용됩니다. 아래는 이를 사용한 예제 코드입니다.

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string str = "Hello, World!";
    char target = 'o';
    int count = std::count(str.begin(), str.end(), target);

    std::cout << "The number of '" << target << "' in the string is: " << count << std::endl;
    return 0;
}

이러한 방법들을 사용하여 C++에서 문자열에서 특정 문자의 개수를 효율적으로 세어볼 수 있습니다.