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

2023. 4. 16. 20:58프로그래머스 - JAVA

문제 설명

문자열 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) {
    String[] answer = new String[(int) Math.ceil((double) my_str.length() / n)];
        int ch = 0;
        for(int i = 0;i<my_str.length();i+=n){
            if(i+n>my_str.length()){
                answer[ch] = my_str.substring(i, my_str.length());
                break;
            }
            else{
                answer[ch] = my_str.substring(i, i+n);
            }
            ch++;
        }
        return answer;
    }
}

 

 

 

 

 

 

출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges