[c++] 문자열에서 숫자 추출하는 방법
첫 번째 방법: 루프를 사용하여 숫자 추출
이 방법은 숫자가 연이어 나열되어 있고, 다른 문자로 둘러싸인 경우에 유용합니다.
#include <iostream>
#include <string>
#include <cctype>
int main() {
std::string text = "abc 123 def 456";
std::string number;
for (char c : text) {
if (std::isdigit(c)) {
number += c;
} else if (!number.empty()) {
std::cout << number << std::endl;
number.clear();
}
}
if (!number.empty()) {
std::cout << number << std::endl;
}
return 0;
}
두 번째 방법: 정규 표현식 사용
정규 표현식을 사용하면 숫자가 특정한 패턴을 따를 때 더 효율적으로 숫자를 추출할 수 있습니다.
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string text = "abc 123 def 456";
std::regex number_regex("\\d+");
auto words_begin = std::sregex_iterator(text.begin(), text.end(), number_regex);
auto words_end = std::sregex_iterator();
for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
std::smatch match = *i;
std::cout << match.str() << std::endl;
}
return 0;
}
이러한 방법들을 사용하여 C++에서 문자열에서 숫자를 추출할 수 있습니다. 필요에 따라서는 다른 방법을 사용할 수도 있으니 상황에 맞게 선택하시면 됩니다.