영어에선 a, e, i, o, u 다섯 가지 알파벳을 모음으로 분류합니다. 문자열 my_string이 매개변수로 주어질 때 모음을 제거한 문자열을 return하도록 solution 함수를 완성해주세요.
| my_string | result |
|---|---|
| "bus" | "bs" |
| "nice to meet you" | "nc t mt y" |
class Solution {
public String solution(String my_string) {
String answer = "";
for(int i=0; i<my_string.length(); i++){
char c = my_string.charAt(i);
switch(c){
case 'a': case 'e': case 'i': case 'o': case 'u':
break;
default:
answer += c;
}
}
return answer;
}
}
class Solution {
public String solution(String my_string) {
String answer = "";
answer = my_string.replaceAll("[aeiou]", "");
return answer;
}
}
반복문을 통해 문자열에서 문자를 하나씩 보면서, switch-case문을 통해 기본 값으로는 문자를 answer 문자열에 더해주고, 모음일 경우에는 하지않고 빠져나가도록 하였다.
정규 표현식의 인자값을 넣어서 replaceAll을 사용하였다.
charAt(i)
문자열에서 특정 문자를 반환할 때 사용하는 함수
String hello = "hello"; char h = hello.charAt(0); char e = hello.charAt(1);
replace()와 replaceAll()
String str = "abcdefg"; System.out.println(str.replace("a", "o").replace("b", "o").replace("c", "o"); // ooodefg System.out.println(str.replaceAll("[abc]", "o")); // ooodefg
정규 표현식
[]: 대괄호 안에 문자가 있는지를 확인한다.
예시: [ab][cd]: a, b 중 한 문자와 c, d 중 한 문자 -> ac ad bc bd[^]: 대괄호 안에 ^ 문자가 있으면 제외한다.
예시: [^a-z]: 알파벳 a부터 z까지를 제외한 모든 문자-: 사이의 문자 혹은 숫자를 의미한다.
예시: [a-z] : 알파벳 a부터 z까지, [a-z0-9]: 알파벳 소문자 전체, 0~9 중 한 문자|: or 연산
예시: [a|b]: a 또는 b
효율적인 코드를 생각한다고 했던게 switch-case였는데..
replaceAll이라는 메서드가 있다니.. 아직 갈 길이 멀다 ~