IT/Algorithm | Coding Test

[프로그래머스 12951] [Java] JadenCase 문자열 만들기

iamhyeon 2025. 2. 25. 16:49

✏️ Solution 1

public class JadenCase문자열만들기 {

    public String solution(String s) {
        String answer = "";

        String[] arr = s.split(" ");

        for (int i=0; i<arr.length; i++) {
            String now = arr[i];

            if (arr[i].length() == 0) {
                answer += " ";
            } else {
                answer += now.substring(0, 1).toUpperCase();
                answer += now.substring(1, now.length()).toLowerCase();
                answer += " ";
            }
        }

        if (s.substring(s.length()-1, s.length()).equals(" ")) {
            return answer;
        }

        return answer.substring(0, answer.length()-1);
    }

    public static void main(String[] args) {
        JadenCase문자열만들기 s = new JadenCase문자열만들기();
        System.out.println(s.solution("3people unFollowed me"));
        System.out.println(s.solution("for the last week"));
    }
    
}

 

 

✏️ Solution 2

public class JadenCase문자열만들기_2 {

    public String solution(String s) {
        String answer = "";

        String[] sp = s.toLowerCase().split("");
        boolean flag = true;

        for (String ss : sp) {
            answer += flag ? ss.toUpperCase() : ss;
            flag = ss.equals(" ") ? true : false;
        }

        return answer;
    }

    public static void main(String[] args) {
        JadenCase문자열만들기_2 s = new JadenCase문자열만들기_2();
        System.out.println(s.solution("3people unFollowed me"));
        System.out.println(s.solution("for the last week"));
    }
    
}

 

 

✏️ Solution 3

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JadenCase문자열만들기_3 {

    public String solution(String s) {
        // 단어의 첫 글자와 나머지 글자를 그룹으로 나누는 정규 표현식을 컴파일한다.
        // \\b: 단어 경계를 나타낸다. 단어의 시작이나 끝을 의미
        // ([\\w]): 단어의 첫 글자를 캡처하는 그룹
        // ([\\w]*): 단어의 나머지 글자를 캡처하는 그룹
        // matcher(s): 입력 문자열 s에 대해 매칭 작업을 수행하는 Matcher 객체를 생성한다.
        Matcher m = Pattern.compile("\\b([\\w])([\\w]*)").matcher(s);
        
        StringBuffer sb = new StringBuffer();

        // 입력 문자열에서 패턴과 일치하는 부분을 찾는다
        while (m.find()) {
            // 매칭된 부분을 대체하여 StringBuffer에 추가한다. 
            m.appendReplacement(sb, m.group(1).toUpperCase() + m.group(2).toLowerCase());
        }
        // 마지막으로 매칭되지 않은 부분을 StringBuffer에 추가한다.
        m.appendTail(sb);

        return sb.toString();
    }

    public static void main(String[] args) {
        JadenCase문자열만들기_3 s = new JadenCase문자열만들기_3();
        System.out.println(s.solution("3people unFollowed me"));
        System.out.println(s.solution("for the last week"));
    }
    
}

2025.02.25 - [IT/JAVA] - Pattern, Matcher Class

 

Pattern, Matcher Class

Java에는 정규식을 활용해 문자열을 검증, 탐색을 돕는 Pattern, Matcher 클래스가 있다Java API  java.util.regex 패키지에 포함되어 있다.  Pattern 클래스  (java.util.regex.Pattern)- 정규 표현식을 정의하는 클

iamsh.tistory.com

 

반응형