코딩테스트/프로그래머스

[숫자 문자열과 영단어]

애플쩀 2022. 6. 13. 05:57
  • for문 안에 if문이 없어도 실행이 된다...  -> 존재하던말던 검사를 해서 그런가보다 
  • replaceAll은 바꿀 문자열에 정규식을 넣을 수 있다는 점이 replace와 다르다.
class Solution {
    public int solution(String s) {
    	String[] mat= {"zero", "one", "two", "three","four","five", "six","seven","eight","nine"};
    		for (int i = 0; i < mat.length; i++) {
		          if(s.contains(mat[i])){
                     s=s.replace(mat[i], Integer.toString(i));
                  }
    		}
    		int answer=Integer.parseInt(s);
    		return answer;
    }
}
class Solution {
    public int solution(String s) {
    //바꿀 문자열을 배열로만들고 
    	String[] mat= {"zero", "one", "two", "three","four","five", "six","seven","eight","nine"};
    	//for문을 돌려서 확인 
        for (int i = 0; i < mat.length; i++) {
		         //전달받은 s에 mat[i]가 존재한다면 
                  if(s.contains(mat[i])){
                  //mat[i]와 i가 일치하기 때문에 i를 일단 string으로 변환해서 대체시켜주고
                     s=s.replace(mat[i], Integer.toString(i));
                  }
    		}
            //이제 모두 숫자로 변환되었으니까 숫자로 변환해주기
    		int answer=Integer.parseInt(s);
    		return answer;
    }
}