String 클래스에서 특정 문자가 포함되어 있는지 확인할 때 3가지 메서드를 사용할 수 있다.
int indexOf(String str)
int indexOf(String str, int fromIndex)
int indexOf(int ch)
int indexOf(int ch, int fromIndex)
예시
public class StringIndexOf {
public static void main(String[] args) {
String str = "hello Java!";
// indexOf(String str)
System.out.println(str.indexOf("he")); //0
System.out.println(str.indexOf("Java")); //6
System.out.println(str.indexOf("java")); //-1, 대/소문자 구분
System.out.println(str.indexOf(" ")); //5, 공백 구분
// indexOf(int ch)
System.out.println(str.indexOf('l')); //2, 'l'을 int형으로 받는 이유는 아스키코드
// indexOf(int ch, int fromIndex)
/* 두번째 파라미터는 start index이므로 index 3부터 문자열을 찾는다. */
System.out.println(str.indexOf('l', 3)); //3
System.out.println(str.indexOf('l', 4)); //-1
}
}
boolean contains(CharSequence s)
예시
public class StringContains{
public static void main(String[] args){
String str = "my java test";
System.out.println(str.contains("java")); //true
System.out.println(str.contains(" my")); //false, 공백 구분
System.out.println(str.contains("JAVA")); //false, 대/소문자 구분
System.out.println(str.contains("java test")); //true
System.out.println(str.contains(" ")); //true
}
}
boolean matches(String regex)
예시
public class StringMatches {
public static void main(String[] args) {
String str = "hello Java!";
System.out.println(str.matches("he")); //false
/*문자열이 정확히 "he" 이여야만 true를 반환*/
System.out.println(str.matches("(.*)he(.*)")); //true
/*(.*)는 0번 이상의 문자가 나오는 경우를 나타내는 정규식이며,
"(.*)he(.*)" 정규식은 문장의 어느 곳에서든 "he"라는 문자열이 나올 경우 true를 반환*/
}
}