특정 문자열 추출하는 방법.
package ch09utility;
public class GetName2 {
public static void main(String[] args) {
final String what = "유재석";
String target = "유재석강호동유재석김철수강호동";
System.out.println("문자열 원본 : " + target);
int cnt = 0; // 발견된 횟수(count)
int idx = -1;
int len = what.length(); //문자열 길이
while (true){
idx = target.indexOf(what); //indexOf로 문자열을 찾으면 발견된 위치의 첫번째 인덱스를 반환. int타입으로 반환.
if(idx == -1){
String imsi = "%s는 더이상 존재하지 않습니다.\n";
System.out.printf(imsi, what);
break;
}else{
target = target.substring(idx +len);
System.out.println("새로 추출된 문자열 :"+ target);
cnt++;
}
String message = "문자열 %s는 %d번 발견되었습니다.";
System.out.printf(message, what, cnt);
}
}
}
int idx = -1;
while (true){
idx = target.indexOf(what);
}
반복문 내에서 target.indexOf(what) 를 호출하여 target 문자열에서 what 문자열이 처음 등장하는 위치를 찾고, 그 값을 idx 변수에 저장한다.
target = target.substring(idx +len); System.out.println("새로 추출된 문자열 :"+ target); cnt++; }
target 문자열을 idx + len 위치 이후부터 끝까지 잘라내어 target에 저장한다.
메서드 | 역할 | 매개변수 타입 | 반환 타입 | 사용 예 |
---|---|---|---|---|
indexOf() |
특정 문자나 문자열의 위치를 반환 | int (문자) 또는 String |
int |
"Hello".indexOf('e') |
substring() |
문자열의 특정 부분(하위 문자열)을 추출 | int 또는 int, int |
String |
"Hello".substring(0, 4) |
'자바 > 자바 기본 라이브러리' 카테고리의 다른 글
"유틸리티"란? (1) | 2025.01.16 |
---|---|
백엔드 개발자가 알아두면 좋은 메서드 모음. (2) | 2025.01.15 |
랜덤 숫자 만들기 - Random(), nextInt() (0) | 2025.01.15 |
java.lang 패키지(암시적 import) (0) | 2025.01.15 |
String 클래스 예제 (0) | 2025.01.15 |