문제 풀기/C#
46. 숫자 문자열과 영단어(Replace 함수)
kagan-draca
2025. 2. 3. 14:52
기본 틀 :
using System;
public class Solution {
public int solution(string s) {
int answer = 0;
return answer;
}
}
문제를 보고 문자열 배열 선언과 동시에 "zero" ~ "nine"으로 초기화 해줬다.
그 후,
반복문을 사용해 해당 문자열 배열을 순회하면서 "zero" ~ "nine"이라는 문자열이 있을 경우 "0" ~ "9"로 바꿔줘야 하는데
이때, Replace 함수를 활용했다.
처음에는 Replace 함수는 "1zerozeroone2345zero"
가 있을 때 "zero"를 "0"으로 변경하면 "10zeroone2345zero" 처럼
하나의 문자열만 변경해주는 줄 알았다.
하지만, 모든 "zero"를 "0"으로 변경해주는 함수였다.
(덕분에 반복문 하나를 더 사용할 필요가 사라졌습니다)
using System;
public class Solution {
public int solution(string s)
{
string[] stringTypeNumber = {"zero","one","two","three","four","five","six","seven","eight","nine"};
for(int i = 0; i < stringTypeNumber.Length; i++)
{
s = s.Replace(stringTypeNumber[i], i.ToString());
}
return int.Parse(s);
}
}