indexOf()
- indexOf(String str)
- indexOf(int ch)
- indexOf(int ch, int fromIndex)
- indexOf(String str, int fromIndex)
indexOf()는 특정 문자나 문자열이 앞에서부터 처음 발견되는 인덱스를 반환하며 만약 찾지 못했을 경우 "-1" 반환한다.
public class IndexOfTest{
puvlic static void main(String[] args) {
String indexOfTestOne = "Hello world";
String indexOfTestTwo = " Hello world ";
System.out.println( indexOfTestOne.indexOf("o") ); // 4
System.out.println( indexOfTestOne.indexOf("x") ); // -1
System.out.println( indexOfTestOne.indexOf("o",5) ); // 7
System.out.println( indexOfTestTwo.indexOf("o") ); // 13
System.out.println( indexOfTestTwo.indexOf("el") ); // 10
}
}
.indexOf("찾을 특정 문자", "시작할위치")
시작할 위치는 생략가능하며 생략할 경우 0번째부터 찾기 시작한다
lastIndexOf()
- lastIndexOf(String str)
- lastIndexOf(int ch)
- lastIndexOf(int ch, int fromIndex)
- lastIndexOf(String str, int fromIndex)
lastindexOf()는 특정 문자나 문자열이 뒤에서부터 처음 발견되는 인덱스를 반환하며 만약 찾지 못했을 경우 "-1" 반환
public class IndexOfTest{
public static void main(String[] args){
String indexOfTestOne = "Hello world";
System.out.println( indexOfTestOne.lastIndexOf("o") ); // 7
System.out.println( indexOfTestOne.lastIndexOf("x") ); // -1
System.out.println( indexOfTestOne.lastIndexOf("o",5) ); // 4
}
}
'Language > JAVA' 카테고리의 다른 글
Wrapper 클래스 (0) | 2023.05.29 |
---|---|
문자열 형변환 toString vs String.valueOf() (0) | 2023.05.25 |
클래스 메서드 VS 인스턴스 메서드 (0) | 2023.05.16 |