본문 바로가기
자료구조 & 알고리즘/문제풀이

JadenCase 문자열 만들기 - 프로그래머스 (Java, Level 2)

by 넬준 2022. 3. 5.

처음 풀이

- 아스키코드 'A' -> 65, 'a' -> 97, 공백 -> 32

 

public String solution(String s) {

    StringBuilder sb = new StringBuilder();

    //앞 단어 공백 확인
    //맨 첫 단어때문에 true로 초기화
    boolean spaceFlag = true;
    int length = s.length();

    for(int i=0; i<length; i++) {
        char next = s.charAt(i);
        if(next>='A' && next<='Z') {
            //대문자
            if(!spaceFlag) {
                //앞이 공백이 아니었다면 소문자로
                next += 32;
            }//if end
        } else if(next>='a') {
            //소문자
            if(spaceFlag) {
                //앞이 공백이었다면 대문자로
                next -= 32;
            }//if end
        }//if~else end

        spaceFlag = (next==32)? true : false;
        sb.append(next);
    }//for end
    
    return sb.toString();
}//solution() end

 

 

다른 풀이

char로 나누지 않고 String으로 나눈다.

바로 앞 문자가 공백이었을 경우,  그 뒤로는 무엇이 오든 간에 모두 대문자로 바꿔준다.

 

public String solution3(String s) {
    StringBuilder sb = new StringBuilder();

    //전체 소문자로
    String allLowerStr = s.toLowerCase();

    //앞 단어 공백 확인
    //맨 첫 단어때문에 true로 초기화
    boolean spaceFlag = true;
    int length = s.length();

    for(int i=0; i<length; i++) {
        String next = allLowerStr.substring(i,i+1);
        //직전 문자가 공백이었다면, 그 다음은 무조건 대문자로!(공백, 알파벳, 숫자 전부)
        sb.append((spaceFlag)? next.toUpperCase() : next);
        spaceFlag = next.equals(" ")? true : false;
    }//for end
    
    return sb.toString();
}//solution3() end

댓글