망공부/코딩테스트

[프로그래머스] 문자열 겹쳐쓰기 (java)

moonmm 2023. 11. 14. 14:08

 

문제

 

 

 

정답코드

 

class Solution {
    public String solution(String my_string, String overwrite_string, int s) {
        //  my_string와 overwrite_string은 숫자와 알파벳으로 이루어져 있습니다.
        String answer = my_string.substring(0,s) + overwrite_string;
        
        if(my_string.length() > answer.length()){
            answer+= my_string.substring(answer.length());
        }
      
        
        return answer;
        
      
    }
}

 

 

substring() 함수를 사용합니다.

인자를 하나만 받는 경우, 인자 두개 받는 경우가 있습니다

 

 

 

 

substring(int index)

 

인자를 하나만 받는 경우

 

String str = "abcdefgh";

str.substring(4);  //'efgh' 출력
string a b c d e f g h
index 0 1 2 3 4 5 6 7

 

이렇게 인덱스 값 이후의 문자열을 출력해줍니다.

 

 

substring(int index1, int index2)

인자를 두개 받는 경우

index1은 문자열 시작지점, index2는 끝지점입니다.

String str2 = "가나다라마바사아";

str2.substring(2,5); //'다라마' 출력

 

string
index 0 1 2 3 4 5 6 7

 

substring(index1, index2) 에서 시작지점의 인덱스틑 포함되지만 끝지점의 인덱스는 포함하지 않습니다