Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

5.4 null과 NullPointerException - 문자열 찾기 indexOf() 본문

이것이 자바다/05 참조 타입

5.4 null과 NullPointerException - 문자열 찾기 indexOf()

빌드이너프 2024. 3. 31. 17:21

문자열에서 특정 문자열의 위치를 찾고자 할 때는 indexOf() 메소드를 사용

indexOf() 메소드는 주어진 문자열이 시작되는 인덱스를 return 한다

 

index 변수에는 3이 저장됨

String subject = "자바 프로그래밍";
int index = subject.indexOf("프로그래밍");
 
0 1 2 3 4 5 6 7

 

만약 문자열이 포함되어 있지 않으면 indexOf() 메소드는 -1을 return 한다

 

주어진 문자열이 포함되어 있는지 여부에 따라 실행 코드를 달리하고 싶다면 if 조건식을 사용할 수 있다

int index = subject.indexOf("프로그래밍");
if(index == -1) {
  //포함되어 있지 않은 경우
} else {
  //포함되어 있는 경우
}

 

 

예제

package ch05.sec05;

public class IndexOfContainsExample {
	public static void main(String[] args) {
		String subject = "자바 프로그래밍";
		
		int location = subject.indexOf("프로그래밍");
		System.out.println(location);
		
		if(location != -1) {
			System.out.println("자바와 관련된 책");
		} else {
			System.out.println("자바와 관련없는 책");
		}
		
		System.out.println("=====================================");
		
		boolean result = subject.contains("자바");
		
		if(result) {
			System.out.println("자바와 관련된 책");
		} else {
			System.out.println("자바와 관련없는 책");
		}
		
	}
}
3
자바와 관련된 책
=====================================
자바와 관련된 책