(java)프로그래머스 코딩테스트 - 문자 반복 출력

navelop·2024년 6월 14일
0

TIL(CODE)

목록 보기
19/20
class Solution {
    //hello의 각 문자를 세 번씩 반복한 "hhheeellllllooo"
    public String solution(String my_string, int n) {
        String answer = "";
        // 각 문자열 중첩 반복문
        for(int i=0; i<my_string.length(); i++){
            for(int j=0; j<n; j++){ // ex) 3번 반복 012<3
                answer += my_string.charAt(i);
            }
        }    
        return answer;
    }
}

charAt() = String 메서드 : 특정 위치에 있는 문자 반환
위 문제에선 hello x 3이 아닌 개별문자 반복이므로 활용


⬇️문자열 반복

package array.ex;

public class Arraycode {

    public static void main(String[] args) {
        System.out.println(solution("hello",3));
    }

    public static String solution(String my_string, int n){
        String answer = "";
        for(int i=0; i<n; i++){
            answer += my_string;
        }
        return answer;
    }
}

hellohellohello

⬇️charAt 메서드 활용 실행문

package array.ex;

public class Arraycode {

    public static void main(String[] args) {
        System.out.println(solution("hello",3));
    }

    public static String solution(String my_string, int n){
        String answer = "";
        for(int i=0; i<my_string.length(); i++){
            for(int j=0; j<n; j++){
                answer += my_string.charAt(i);
            }
        }
        return answer;
    }
}

0개의 댓글