Light Blue Pointer
본문 바로가기
Coding Test

[프로그래머스]문자열 다루기 기본

by Greedy 2023. 11. 20.

문제 주소

https://school.programmers.co.kr/learn/courses/30/lessons/12918

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문자열 s의 길이가 4 혹은 6이고, 숫자로만 구성돼있는지 확인해주는 함수, solution을 완성하세요. 예를 들어 s가 "a234"이면 False를 리턴하고 "1234"라면 True를 리턴하면 됩니다.

제한 사항

  • s는 길이 1 이상, 길이 8 이하인 문자열입니다.
  • s는 영문 알파벳 대소문자 또는 0부터 9까지 숫자로 이루어져 있습니다.

입출력 예

s return

"a234" false
"1234" true

풀이 과정

⭐String match()

String이 특정 패턴의 문자열을 포함하는지 확인할 수 있음

문자열에 정규표현식(regex)이 일치하는지를 boolean으로 리턴

 

Regular Expression(Regex) Patterns

[abc] Find one character from the options between the brackets

[^abc] Find one character NOT between the brackets

[0-9] Find one character from the range 0 to 9

Metacharacters : characters with a special meaning

[ | ] Find a match for any one of the patterns separated by  as in: cat|dog|fish 

[ . ] Find just one instance of any character 

[ ^ ] Finds a match as the beginning of a string as in: ^Hello 

[ $ ] Finds a match at the end of the string as in: World$ 

[ \d ] Find a digit

[ \s ] Find a whitespace character

[ \b ] Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b

[ \uxxxx ] Find the Unicode character specified by the hexadecimal number xxxx 

Quantifiers : Quantifiers define quantities

n+  Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n{x} Matches any string that contains a sequence of X n's
n{x,y} Matches any string that contains a sequence of X to Y n's
n{x,} Matches any string that contains a sequence of at least X n's

제출 코드

class Solution {
    public boolean solution(String s) {
        boolean answer = true;
        if((s.length()==4)|(s.length()==6)){
            for(int i=0; i<s.length(); i++){
                String str = ""+s.charAt(i);
                if(!str.matches("[0-9]")){
                    answer = false;
                    break;
                }
            }
        }else{
            answer = false;
        }
        return answer;
    }
}

⚠️matches는 한글자 String에밖에 적용 못 하는듯

 

다른 사람의 풀이

class Solution {
  public boolean solution(String s) {
      if(s.length() == 4 || s.length() == 6){
          try{
              int x = Integer.parseInt(s);
              return true;
          } catch(NumberFormatException e){
              return false;
          }
      }
      else return false;
  }
}

신기한데 다들 실무에서 예외처리식으로 이렇게하면 안된다고 함 ㅋㅋ 

import java.util.*;

class Solution {
  public boolean solution(String s) {
        if (s.length() == 4 || s.length() == 6) return s.matches("(^[0-9]*$)");
        return false;
  }
}

나랑 비슷한데 훨씬 짧다 ㅜ

나는 String matches로 한개씩밖에 비교할 줄 모르는데 저렇게 쓰면 길이가 2 이상인 String도 돌아가나봄

⭐s.matches("(^[0-9]*$)")

class Solution {
    public boolean solution(String s) {
        boolean answer = false;
        if((s.length()==4)|(s.length()==6)){
            if(s.matches("(^[0-9]*$)")){
                answer = true;
            }
        }
        return answer;
    }
}

내가 짜면 이렇게 됨

s.matches가 어차피 true가 나오니까 s.matches 자체를 돌려보내는게 더 짧게하는 방법인듯