1. indexOf( )

  • 대상 문자열에서 찾을 문자의 index 값을 반환한다
indexOf(String str) 대상 문자열에 인자값으로 주어지는 String값이 있는지 검색
indexOf( char ch) 대상 문자열에 인자값으로 주어지는 char값이 있는지 검색
indexOf(String str, int fromIndex) 대상 문자열에 첫번째 인자값으로 주어지는 String값이 있는지 두번째 인자값의 index부터 검색
indexOf(char ch, int fromIndex) 대상 문자열에 첫번째 인자값으로 주어지는 char값이 있는지 두번째 인자값의 index부터 검색
public class String_indexOf {
    public static void main(String[] args) {

    String str = "Hello welcome to develop world!!";
                //01234567890123456789012345678901

        System.out.println(str.indexOf("welcome")); //문자열 검색 -> 6
        System.out.println(str.indexOf("to")); //문자열 검색 -> 14

        System.out.println(str.indexOf("t")); //문자 검색 -> 14
        System.out.println(str.indexOf("w")); //문자 검색 -> 6

        System.out.println(str.indexOf("welcome",10)); //문자열을 10번째 index부터 검색 -> -1
        System.out.println(str.indexOf("to",10)); //문자열을 10번째 index부터 검색 -> 14
        System.out.println(str.indexOf("world",10)); //문자열을 10번째 index부터 검색 -> 25

        System.out.println(str.indexOf("t",10)); //문자를 10번째 index부터 검색 -> 14
        System.out.println(str.indexOf("w",10)); //문자를 10번째 index부터 검색 -> 25
        System.out.println(str.indexOf("p",10)); //문자를 10번째 index부터 검색 -> 23

        if(str.indexOf("welcome")!=-1) {
            System.out.println("문자가 포함되어 있습니다");
        } else {
            System.out.println("문자가 포함되어 있지 않습니다");
        }
    }
}

 

2. contains( )

  • 문자열에 검색하려는 문자가 있는지 확인한다
  • 문자가 있으면 true, 없으면 false 값을 반환한다
public class String_contains {
    public static void main(String[] args)  {
        String str = "Hello welcome to develop world!!";

        if(str.contains("welcome")) {
            System.out.println(true);
        }else {
            System.out.println(false);
        }
    }
}

 

3. matches( )

matches는 정규식을 이용하여 문자열을 검색한다

영문자나 숫자등의 정규표현식이 대상 문자열에 있는지 확인할 경우에 사용하면 편리하다

boolean 형식으로 결과 값을 리턴한다

public class String_matches {
    public static void main(String[] args)  {
        String s = "Hello welcome to develop world!!";

        //특정 문자열 검색
        if(s.matches(".*welcome.*")) {
            System.out.println(true);
        }else {
            System.out.println(false);
        }

        //영문자 검색
        if(s.matches(".*[a-zA-Z].*")) {
            System.out.println(true);
        }else {
            System.out.println(false);
        }

        //숫자 검색
        if(s.matches(".*[0-9].*")) {
            System.out.println(true);
        }else {
            System.out.println(false);
        }
    }
}

'JAVA > 명령어' 카테고리의 다른 글

Java - 명령어 - 문자열 특정값 가져오기  (0) 2022.09.16
Java - 명령어 - 정규표현식  (0) 2022.09.16

+ Recent posts