java

[프로그래머스 - 자바] 숨어있는 숫자의 덧셈(2)

tues 2023. 9. 1. 12:01

문제 설명

 

 

 

솔루션

 

 

class Solution {
    public int solution(String my_string) {
        int answer = 0;
        String[] str_arr = my_string.split("[a-zA-Z]+");//알파벳 쪼개서 String 배열 만들기 
        for(int i = 0; i < str_arr.length; i++){
            if(str_arr[i].matches("[0-9]+")){//숫자인지 
                answer += Integer.parseInt(str_arr[i]);//Integer.parseInt해서 answer 더하기
            }
        }
        return answer;
    }
}

 

다른 방법

class Solution {
    public int solution(String my_string) {
        int answer = 0;

        String[] str = my_string.replaceAll("[a-zA-Z]", " ").split(" ");//알파벳 죄다 없애기 

        for(String s : str){
            if(!s.equals("")) answer += Integer.valueOf(s);//빈칸이 아닐경우 더하기 
        }

        return answer;
    }
}