본문 바로가기

CodingTest/Java

[프로그래머스] 잘라서 배열로 저장하기 _JAVA

728x90
반응형

문자열 my_str과 n이 매개변수로 주어질 때, 

my_str을 길이 n씩 잘라서 저장한 배열을 return하도록 solution 함수를 완성해주세요.

 

제한사항

  • 1 ≤ my_str의 길이 ≤ 100
  • 1 ≤ n  my_str의 길이
  • my_str은 알파벳 소문자, 대문자, 숫자로 이루어져 있습니다.
class Solution {
    public String[] solution(String my_str, int n) {
    	//Math.ceil => 올림
        int cnt = (int) Math.ceil((double)my_str.length()/n);
        int j = 0;
        String[] answer = new String[cnt];

        for(int i=0; i<cnt; i++) {
            if(my_str.length() % n == 0) {
                answer[i] = my_str.substring(j, j+n);
            } else {
                if(i == cnt - 1) {
                    answer[i] = my_str.substring(j);
                } else {
                    answer[i] = my_str.substring(j, j+n);
                }
            }
            j += n;
        }
        return answer;
    }
}
728x90
반응형