프로그래머스 Lv2 - JadenCase 문자열 만들기 문제
이전 문자를 기록하는 beforeStr 변수를 두어 이전 문자를 기준으로 맞는 조건에 따라 대소문자를 변경하도록 했다. 문제 내용 중 "공백문자가 연속해서 나올 수 있습니다."에 유의하여 풀어야 했다!
글을 작성하면서 보니 beforeStr을 boolean값을 가진 flag 변수를 통해 해결할수도 있어 보이고, 조건들도 조금 더 축약할 수 있을것 같다.
JadenCase.java
package com.example.Programmers.Lv2;
/**
* 프로그래머스 Lv2 - JadenCase 문자열 만들기
*/
public class JadenCase {
public String solution(String s) {
String answer = "";
String[] arr = s.split("");
String beforeStr = "";
for (int i = 0; i < arr.length; i++) {
if (i == 0) {
beforeStr = arr[i];
}
if (arr[i] == " ") {
answer += arr[i];
} else {
boolean isNum = arr[i].replaceAll("[0-9]", "").length() == 0;
if (isNum) {
answer += arr[i];
} else if (!isNum && !beforeStr.equals(" ") && i == 0) {
answer += arr[i].toUpperCase();
} else if (!isNum && !beforeStr.equals(" ")) {
answer += arr[i].toLowerCase();
} else if (!isNum && beforeStr.equals(" ")) {
answer += arr[i].toUpperCase();
}
beforeStr = arr[i];
}
}
return answer;
}
}
JadenCaseTest.java
package com.example.Programmers.Lv2;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class JadenCaseTest {
@Test
public void testJadenCase() {
JadenCase jdc = new JadenCase();
String result1 = jdc.solution("3people unFollowed me");
String result2 = jdc.solution("for the last week");
String result3 = jdc.solution(" for the what 1what ");
assertEquals("3people Unfollowed Me", result1);
assertEquals("For The Last Week", result2);
assertEquals(" For The What 1what ", result3);
}
}