[c++] 문자열에서 공백의 개수 세는 방법

먼저, 아래와 같이 std::stringfind 함수와 반복문을 사용하여 공백을 찾고, 각 공백의 위치를 찾은 후 개수를 세는 방법이 있습니다.

#include <iostream>
#include <string>

int countSpaces(const std::string& str) {
    int spaces = 0;
    size_t pos = str.find(' ');
    while (pos != std::string::npos) {
        spaces++;
        pos = str.find(' ', pos + 1);
    }
    return spaces;
}

int main() {
    std::string text = "This is a sample sentence with spaces.";
    int spaceCount = countSpaces(text);
    std::cout << "Number of spaces: " << spaceCount << std::endl;
    return 0;
}

또 다른 방법은 아래와 같이 범위 기반 for문을 사용하여 문자열의 각 문자를 순회하면서 공백인지 확인하는 방법도 있습니다.

#include <iostream>
#include <string>

int countSpaces(const std::string& str) {
    int spaces = 0;
    for (char c : str) {
        if (c == ' ') {
            spaces++;
        }
    }
    return spaces;
}

int main() {
    std::string text = "This is a sample sentence with spaces.";
    int spaceCount = countSpaces(text);
    std::cout << "Number of spaces: " << spaceCount << std::endl;
    return 0;
}

두 가지 방법 중에 원하는 방법을 선택하여 사용할 수 있습니다.