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

[Lv.0] 문자열 뒤의 n글자

민톨이 2024. 7. 20. 15:42
728x90

📋 문제

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

 

📋 입출력 예시

 

📋풀이

class Solution {
    public String solution(String my_string, int n) {
        String answer = "";
       answer=my_string.substring(my_string.length()-n);
        return answer;
    }
}

 

📌 .substring()

문자열자르기

substring(startIndex)

- startIndex부터 끝까지 리턴 

-문제에서 뒤의 n글자로 이루어진 = 뒤의 n글자부터 시작한 뒤의 n글자부터 시작하려면 startIndex에서 - n을 해주면 된다.

❗️ 음수값이나 범위 초과 Index넣으면 StringIndexOutOfBoundException 뜸 (파이썬이랑 헷갈려서 썼다가 이거 뜸 - -)

 

+ substring(startIndex,endIndex)

- startIndex부터 endIndex까지 리턴