자바 String의 indexOf()와 lastIndexOf()는 String에서 특정 문자열의 인덱스를 찾는데 사용하는 메서드이다.
indexOf(String) : 첫 번째 문자열부터 찾고, 문자열의 시작 index를 리턴.
indexOf(String, int) : 시작 위치를 부여, 부여된 위치부터 시작하여 문자열의 위치 index를 리턴
두 메서드 모두 원하는 String 못찾으면 -1을 리턴 한다.
String hello = "HelloWorld HelloWorld";
System.out.println(hello.indexOf("World"));
System.out.println(hello.indexOf("World", 6));
System.out.println(hello.indexOf("World", 14));
// 결과
// 5
// 16
// 16
lastIndexOf(String) : indexOf와 동일, 맨 뒤에서부터 찾고 싶은 경우 사용
lastIndexOf(String, int) : indexOf와 동일, 맨뒤 기준으로 찾고 싶은 경우 사용
String hello = "HelloWorld HelloWorld";
System.out.println(hello.lastIndexOf("World"));
System.out.println(hello.lastIndexOf("World", 6));
System.out.println(hello.lastIndexOf("World", 14));
// 결과
// 16
// 5
// 5
'개념 창고 > JAVA' 카테고리의 다른 글
[Java] char는 사실 문자가 아닌 정수다. (0) | 2022.12.08 |
---|---|
char를 문자열로 변환하는 방법(3가지) (0) | 2022.12.08 |
[JAVA] charAt() (0) | 2022.12.07 |
[JAVA] 대소문자 변환 & 비교 (toUpperCase, toLowerCase, equalsIgnoreCase) (0) | 2022.12.07 |
[JAVA] legnth / length() / size() 차이 및 사용법 (0) | 2022.12.06 |