문제
문자열의 문자를 하나씩 검사하여 숫자면 그대로 s에 추가하고, 문자라면 숫자로 변환하여 저장한다.
package kakao.intern2021;
import java.util.*;
public class Q1 {
public static void main(String[] args) {
String s = "one4seveneight";
s = "23four5six7";
s = "2three45sixseven";
s = "123";
System.out.println("solution = " + solution(s));
}
public static int solution(String s) {
int answer = 0;
int start = -1;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 'a' && c <= 'z') {
if (start == -1) {
// 변환할 부분 문자열의 시작 인덱스
start = i;
}
String subString = s.substring(start, i + 1);
if (subString.equals("zero")) {
answer *= 10;
answer += 0;
start = -1;
} else if (subString.equals("one")) {
answer *= 10;
answer += 1;
start = -1;
} else if (subString.equals("two")) {
answer *= 10;
answer += 2;
start = -1;
} else if (subString.equals("three")) {
answer *= 10;
answer += 3;
start = -1;
} else if (subString.equals("four")) {
answer *= 10;
answer += 4;
start = -1;
} else if (subString.equals("five")) {
answer *= 10;
answer += 5;
start = -1;
} else if (subString.equals("six")) {
answer *= 10;
answer += 6;
start = -1;
} else if (subString.equals("seven")) {
answer *= 10;
answer += 7;
start = -1;
} else if (subString.equals("eight")) {
answer *= 10;
answer += 8;
start = -1;
} else if (subString.equals("nine")) {
answer *= 10;
answer += 9;
start = -1;
}
} else {
answer *= 10;
answer += Integer.parseInt(String.valueOf(c));
}
}
return answer;
}
}
package kakao.intern2021;
import java.util.*;
public class Q1 {
public static void main(String[] args) {
String s = "one4seveneight";
s = "23four5six7";
s = "2three45sixseven";
s = "123";
System.out.println("solution = " + solution(s));
}
public static int solution(String s) {
String[] stringNums = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
for (int i = 0; i < stringNums.length; i++) {
s = s.replaceAll(stringNums[i], String.valueOf(i));
}
System.out.println("s = " + s);
return Integer.parseInt(s);
}
}