알고리즘/프로그래머스

특정 패턴만큼 문자열 자르기

prime9999 2023. 5. 31. 17:09
300x250

솔루션1

public static String[] solution(String my_str, int n) {
    String[] answer   = new String[(my_str.length() + n - 1) / n]; // 문자열 길이에서 n만큼 나눈 몫으로 배열 생성
    String addData    = "";
    int    cnt        = 0;
    int    firstSubIndex = 0;
    int    lastSubIndex  = n;
    int    increase      = n;
    for(int i = 0; i < my_str.length(); i++){ //한글자씩 처리
        int lastNum = my_str.length()-1;
        if(i == (increase-1) || i == lastNum){ //자르려는 길이일땐 배열에 담고 마지막 일땐 마지막 만큼만
            addData     += my_str.substring(firstSubIndex,(lastNum == i?my_str.length():lastSubIndex));
            answer[cnt] = addData;
            addData     = ""; // 원하는 만큼 담고 초기화
            cnt++;         //다음 배열에 담기위해서 증가.
            firstSubIndex = i+1;
            lastSubIndex  = n+n;
            increase = increase + increase;
        }
    }
    return answer;
}

 

솔루션2(해당 솔루션은 프로그래머스 내에서도 별로 없다 다만 JAVA8?이후부터 제공된다)

public static String[] solution2(String my_str, int n) {
    String[] answer = my_str.split(my_str,n);
    return answer;
}
728x90