문자열 my_string이 매개변수로 주어질 때, my_string 안에 있는 숫자만 골라 오름차순 정렬한 리스트를 return 하도록 solution 함수를 작성해보세요.
숫자만 골라 List 객체에 담기 위해 아스키코드를 이용했다. List 객체에 담을 때 charAt(i)로 골라낸 숫자를 파싱해 List<Integer> 객체에 담으려고 했었는데, '잘라내기 - 문자열로 파싱 - Integer로 파싱'하는 과정이 너무 복잡할 뿐더러 toArray() 메서드를 이용해 반환 타입인 배열로 변환할 때 Object[] cannot be converted to int[] 에러가 발생했다.
int와 같은 기본형의 데이터일 경우 Wrapper 클래스로 자동 형변환 해주지 않기 때문에 사용에 제약이 있다는 사실을 매번 잊는 것 같다. 하하
그래서 우선 String 타입으로 List 객체에 담은 뒤, Collections.sort()로 오름차순을 해주고 for문을 통해 루프를 돌며 Integer.parseInt()로 파싱한 숫자들을 정수형 배열에 넣어주었다.
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
class Solution {
public int[] solution(String my_string) {
List<String> intList = new ArrayList<>();
for(int i=0; i<my_string.length(); i++){
if(!(my_string.charAt(i) >= 97 && my_string.charAt(i) <= 122)){
intList.add(String.valueOf(my_string.charAt(i)));
}
}
Collections.sort(intList);
int[] answer = new int[intList.size()];
for(int i=0; i<intList.size(); i++){
answer[i] = Integer.parseInt(intList.get(i));
}
return answer;
}
}
