공부/Java
[Java] 문자열 반복 메서드 repeat()
피치콩
2023. 12. 26. 20:10
🍑note
프로그래머스에서 문제 풀다가 알게 된 repeat()
나는 해당 문제를 for문을 이용해서 출력했는데,
다른 사람 풀이를 보니 repeat()를 이용해서 매우 간단하게 문자열을 반복했다.
파이썬과 달리 자바에서는 * 연산자를 이용한 문자열 반복이 불가하지만,
자바11 부터는 repeat 메서드를 이용하면 파이썬처럼 편하게 문자열을 반복할 수 있다!
repeat() ?
str.repeat(count);
- 자바 11부터 새로 추가된 String 메서드
- 문자열을 count 수만큼 연결하여 문자열을 반환
- 문자열이 비어있거나 count의 수가 0이면 빈 문자열을 반환
- count의 수가 음수인 경우 IllegalArgumentException 발생 (잘못된 인자값을 메서드에 넘겨주었을 때 발생)
문제
💻 프로그래머스 - 문자열 반복해서 출력하기 (Lv.0)
https://school.programmers.co.kr/learn/courses/30/lessons/181950
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이 (1)
💡 for문을 이용한 문자열 반복 출력
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
int n = sc.nextInt();
// for문을 이용한 문자열 반복 출력
for(int i = 0; i < n; i++){
System.out.print(str);
}
sc.close();
}
}
풀이 (2)
💡 repeat()를 이용한 문자열 반복 출력
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
int n = sc.nextInt();
// repeat()를 이용한 문자열 반복 출력
System.out.print(str.repeat(n));
sc.close();
}
}
참고문헌
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#repeat(int)
String (Java SE 11 & JDK 11 )
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argum
docs.oracle.com