9. 핸드폰 번호 가리기

김영민·2022년 1월 27일
0

문제📃

1. 문제 설명

프로그래머스 모바일은 개인정보 보호를 위해 고지서를 보낼 때 고객들의 전화번호의 일부를 가립니다.
전화번호가 문자열 phone_number로 주어졌을 때, 전화번호의 뒷 4자리를 제외한 나머지 숫자를 전부 *으로 가린 문자열을 리턴하는 함수, solution을 완성해주세요.

2. 제한 조건

s는 길이 4 이상, 20이하인 문자열입니다.

3.입출력 예

phone_numberreturn
"01033334444""***4444"
"027778888""*8888"

풀이

나의 정답👨‍💻

public class HideCellPhoneNum {	

    //문자열을 매개변수로 받고, 문자열을 리턴값으로 돌려주는 메소드 생성
    public String solution1(String phone_number) {
        String answer = "";
        
        // 문자열 'phone_number'의 글자들를 한 글자씩 배열에 집어 넣음
        String[] num = phone_number.split("");        
        
        for (int i = 0; i < num.length; i++) {
        
            // num에 있는 객체의 개수보다 4만큼 적게 돌렸을 때는
            if (i < num.length - 4) {
                //'answer'에 "*"을 붙이고,
                answer += "*";
                
            // 그렇지 않을 때는(즉, 반복문이 나머지 4자리를 돌 때는)
            } else {
                //'num'의 i번째에 있는 객체를 붙임
                answer += num[i];
            }    		        		
        }
        return answer;
    }

심화정답 🏆

    public String solution2(String phone_number) {
    
    	// 문자열 'phone_number'를 문자형으로 구성된 배열로 변경
        char[] ch = phone_number.toCharArray();
        
        // 문자형 배열 'ch'의 객체 수보다 4보다 적은 만큼 반복문을 돌리는데
        for(int i = 0; i < ch.length - 4; i ++){
            
            // 반복문이 돌아간 'ch'의 객체는 '*'로 변경
            ch[i] = '*';
        }
        //배열 'ch'를 문자열로 변경해서 리턴값을 돌려줌
        return String.valueOf(ch);
     }

테스트용 코드🎯

    public static void main(String[] args) {
        HideCellPhoneNum hidecellphonenum = new HideCellPhoneNum();
		
        String phone_number1 = "01033334444";
        String phone_number2 = "027778888";
		
        System.out.println(hidecellphonenum.solution1(phone_number1)); // *******4444 출력
        System.out.println(hidecellphonenum.solution1(phone_number2)); // *****8888 출력
        
        System.out.println(hidecellphonenum.solution2(phone_number1)); // *******4444 출력
        System.out.println(hidecellphonenum.solution2(phone_number2)); // *****8888 출력
    }
}
profile
Macro Developer

0개의 댓글