[c++] C++에서의 문자열에서 숫자만 추출하는 방법

문자열의 각 문자 확인하여 숫자 추출

#include <iostream>
#include <string>
#include <cctype>

int main() {
    std::string str = "a1b2c3";
    std::string numbers;

    for (char c : str) {
        if(std::isdigit(c)) {
            numbers += c;
        }
    }

    std::cout << "숫자만 추출된 결과: " << numbers << std::endl;
    return 0;
}

정규표현식을 사용하여 숫자 추출

C++11부터 정규표현식을 사용할 수 있습니다. 아래는 std::regex를 사용하여 숫자를 추출하는 예제입니다.

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

int main() {
    std::string str = "a1b2c3";
    std::regex numRegex("[0-9]+");
    std::smatch match;

    while (std::regex_search(str, match, numRegex)) {
        std::cout << "숫자만 추출된 결과: " << match.str() << std::endl;
        str = match.suffix().str();
    }

    return 0;
}

위의 예제 코드에서는 각각의 방법을 사용하여 문자열에서 숫자를 추출하는 방법을 보여주었습니다.

이러한 방법들을 사용하여 C++에서 문자열에서 숫자를 추출할 수 있습니다.