프로그래머스 숫자 문자열과 영단어 C++

이선아·2022년 2월 8일
2

영단어를 숫자로 변환하는 문제, 치환해주기 위해 regex_replace 사용 #include <regex> 포함!
벡터 스트링에 영단어 0부터 9까지를 넣어준다.

s = regex_replace(s, regex(word[i]), to_string(i));

위와 같은 형식 ☝🏻

📌 문자열 s 중에서 word[i] 에 있는 문자열이 발견되면 i 로 치환해준다.

숫자 문자열과 영단어.cpp

#include <string>
#include <vector>
#include <regex>

using namespace std;

int solution(string s) { 
    vector<string> word = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    
    for(int i = 0; i < 10; i++) {
        s = regex_replace(s, regex(word[i]), to_string(i));
    }
    
    return stoi(s);
}

stoi(string to int). s 는 스트링이기 때문에 int형으로 변환하여 리턴해준다.

profile
깃허브 놀러오세용 -> Tistory로 블로그 이전합니다.

0개의 댓글