본문 바로가기
알고리즘

java,알고리즘] 문자열에서 숫자만 추출하기

by 완기 2021. 10. 5.
728x90
반응형

입력받은 문자열에서 숫자만 추출하여 int형으로 리턴하기.

 

입력 예 :

0sads21a0w8ws87

 

출력 예 :

210887

 

내가 풀었던 방법 1:

public class Main {

   public static void main(String[] args) {
      Main main = new Main();
      System.out.println(main.find("0sads21a0w8ws87"));
   }
   public int find(String input) {
      StringBuilder sb = new StringBuilder();
      int length = input.length();
      for (int i = 0; i < length; i++) {
         try {
            sb.append(Integer.parseInt(String.valueOf(input.charAt(i))));
         } catch (Exception e) {
            continue;
         }
      }
      return Integer.parseInt(sb.toString());
   }
}

처음으로 생각했던 방법은 문자열의 길이만큼 반복문을 돌면서, 

 

각 원소를 비교하는 것이다.

숫자가 아니면 parse 하다가 Exception이 발생하기 때문에 try catch를 통해 숫자인지, 아닌지 판단했고 

 

숫자라면 String Builder에 원소를 추가했다.

출력은 의도된 대로 잘 나왔지만, 몇 가지 문제점을 유추해 볼 수 있었다.

 

1.try catch를 쓰긴 했지만, Exception이 발생한다는 점

2. 반복문을 사용해서 리소스가 불필요하게 많이 사용된다는 점.

 

이런 점을 해결하기 위해 String 오브젝트의 Replace All 사용해 정규 표현식을 사용하기로 마음먹고

 

정규표현식을 찾아봤다.

 


 내가 풀었던 방법 2:

public class Main {

   public static void main(String[] args) {
      Main main = new Main();
      System.out.println(main.find("0ads21a0w8ws87"));
   }

   public int find(String input) {
      return Integer.parseInt(input.replaceAll("[a-z]", ""));
   }
}
300x250

replace all에 정규표현식을 이용해 a~z까지 문자열을 빈 문자열로 바꿔줬다.

 

마찬가지로 출력은 잘 됐지만, 대문자를 넣어봤더니 바뀌지 않았다.

 

구글링을 해본 결과 방법은 간단했다.

 

replaceAll("[a-z|A-Z]", "")

 

| 를 통해 마치 if의 or 조건처럼 사용 가능했고, 결과는 잘 바뀌었다.

 

public class Main {
   public static void main(String[] args) {
      Main main = new Main();
      System.out.println("input = \"0aABCds21a0w8ws87\"");
      System.out.println(main.find("0aABCds21a0w8ws87"));
   }

   public int find(String input) {
      return Integer.parseInt(input.replaceAll("[a-z|A-Z]", ""));
   }
}

 

 

728x90
728x90

댓글