본문 바로가기

프로그래머스/lv0

잘라서 배열로 저장하기

/* 잘라서 배열로 저장하기
 * 문자열 my_str과 n이 매개변수로 주어질 때,
 * my_str을 길이 n씩 잘라서 저장한 배열을 return하도록 solution 함수를 완성해주세요.
 *
 * my_str               n   result
 * "abc1Addfggg4556b"   6   ["abc1Ad", "dfggg4", "556b"]
 * "abcdef123"          3   ["abc", "def", "123"]
 *
 * "abc1Addfggg4556b" 를 길이 6씩 잘라 배열에 저장한 ["abc1Ad", "dfggg4", "556b"]를 return
 * "abcdef123" 를 길이 3씩 잘라 배열에 저장한 ["abc", "def", "123"]를 return
 *
 * 입출력 예 #1의 경우 "abc1Addfggg4556b"를 길이 6씩 자르면
 * "abc1Ad", "dfggg4" 두개와 마지막 "556b"가 남습니다.
 * 이런 경우 남은 문자열을 그대로 배열에 저장합니다.
 */
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class programmer_0_6 {
    static String a1 = "abc1Addfggg4556b";  static int n1 = 6;
    static String a2 = "abcdef123";         static int n2 = 3;
 
    public String[] solution(String my_str, int n) {
        int size = 0;
        if(my_str.length()%n != 0)  size = my_str.length()/+ 1;
        else                        size = my_str.length()/n;
        
        String[] answer = new String[size];
 
        int idx = 0;
        for(int i = 0; i < my_str.length(); i = i + n){
            System.out.println("i = " + i + " / end = " + (i + n));
 
            if((i+n) > my_str.length())     answer[idx] = my_str.substring(i, my_str.length());
            else                            answer[idx] = my_str.substring(i, i + n);
 
            idx++;
        }
        return answer;
    }
    public static void main(String args[]){
        programmer_0_6 t = new programmer_0_6();
 
        System.out.println("---------------------------------------");
        System.out.println("result = " + t.solution(a1, n1));
        System.out.println("---------------------------------------");
        System.out.println("result2 = " + t.solution(a2, n2));
        System.out.println("---------------------------------------");
    }
}
cs

'프로그래머스 > lv0' 카테고리의 다른 글

종이 자르기  (0) 2022.12.06
문자열 밀기  (0) 2022.12.06
7의 개수  (0) 2022.12.06
문자열 정렬하기(2)  (0) 2022.12.06
세균 증식  (0) 2022.12.06