코딩테스트/프로그래머스

[프로그래머스] 문자열의 앞의 n글자 (Level 0, JavaScript)

방혜진 2024. 3. 27. 13:21

문제

출처: 프로그래머스 코딩 테스트 연습,

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

 

프로그래머스

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

programmers.co.kr

문자열 my_string과 정수 n이 매개변수로 주어질 때,
my_string의 앞의 n글자로 이루어진 문자열을 return 하는 solution 함수를 작성해 주세요.

 

 

❓ 나의 풀이

function solution(my_string, n) {
    
    return result = my_string.substring(0, n);

}

앞에서부터 n글자로 이루어진 문자열 == 첫 번째부터 n번째까지 잘라라!

문자열을 자르는 substring() 메서드를 사용했다.

 

 

str.substring(indexStart [, indexEnd])

  • indexStart: 반환 문자열의 시작 인덱스
  • indexEnd: 옵션, 반환문자열의 마지막 인덱스 (포함하지 않음, 생략 가능)
  • 반환값: 기존문자열의 부분 문자열을 반환
  1. indexEnd가 생략된 경우는, 모든 문자를 반환
  2. indexStart와 indexEnd가 같을 경우는, 빈 문자열을 반환
  3. indexStart가 indexEnd보다 큰 경우는, 두 개의 인자가 바뀐 듯 작동
  4. str.length보다 큰 인자 값을 가지는 경우는, str.length로 처리

 

예시

let anyString = "CuteDog";

// Displays 'C'
console.log(anyString.substring(0, 1));
console.log(anyString.substring(1, 0));

// Displays 'CuteDo'
console.log(anyString.substring(0, 6));

// Displays 'Do'
console.log(anyString.substring(4, 6));
console.log(anyString.substring(6, 4));

// Displays 'CuteDog'
console.log(anyString.substring(0, 7));
console.log(anyString.substring(0, 10));