본문 바로가기
코딩테스트/LV. 0

LV. 0 :: 잘라서 배열로 저장하기

by KUROMI98 2023. 1. 23.

https://school.programmers.co.kr/learn/courses/30/lessons/120913

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

function solution(str, n) {
    var arr = [];
    
    for (i=0; i<Math.floor(str.length/n); i++)
    {   // slice 함수를 써서 분리한 후 arr에 넣어준다.
        arr[i]=str.slice(i*n, i*n+n);
    } 
    
    if (str.length%n!==0)
    {   // 문자열의 길이가 n으로 나누어떨어지지 않는 경우
        arr.push(str.slice(str.length-str.length%n, str.length));
        // 나누어떨어지지 않은 문자열만큼 arr의 맨 뒤에 추가해준다.
    }
    
    return arr;
}

+230515

const solution = (my_str, n) => {
    let answer = [];
    for(i=0; i<my_str.length; i+=n) { answer.push(my_str.slice(i, i+n)); }
    return answer;
}

230916 C++

#include <string>
#include <vector>

using namespace std;

vector<string> solution(string my_str, int n) {
    vector<string> result;
    for(int i=0; i<my_str.size(); i += n){ 
        result.push_back(my_str.substr(i, n));
    }
    return result;
}

'코딩테스트 > LV. 0' 카테고리의 다른 글

LV. 0 :: OX퀴즈  (0) 2023.01.24
LV. 0 :: 문자열 계산하기  (0) 2023.01.24
LV. 0 :: 가까운 수  (0) 2023.01.23
LV. 0 :: A로 B 만들기  (0) 2023.01.23
LV. 0 :: 최댓값 만들기 2  (0) 2023.01.23

댓글