성장일기

 문자열 관련 문제를 풀다보면 문자열에서 특정 문자를 찾거나 위치를 기반으로 문제를 해결해야 하는 경우가 있다.

 

indexOf()


 문자열에서 해당 문자 혹은 문자열의 인덱스를 반환해주는 함수이다.

만약 해당 문자가 문자열에 없으면 -1을 리턴한다.

String s = "Hello welcome to the this place";

s.indexof("welcome");	// 문자열 검색
s.indexof("t");		// 단어 검색
s.indexof("welcome", 10);	// 10번째 index부터 문자열 검색
s.indexof("t", 10);		// 10번째 index부터 단어 검색

 

contains()


 문자열에서 해당 문자 혹은 문자열이 포함되어있는 여부를 boolean값으로 반환해주는 함수이다.

String s = "Hello welcome to the this place";

if(s.contains("welcome")) {
    System.out.println("문자가 포함되어 있습니다.");
}else {
    System.out.println("문자가 포함되어 있지 않습니다.");
}

 

 

matches()


		String s = "Hello welcome to the this place";
		
        //특정 문자열 검색
        if(s.matches(".*welcome.*")) {
            System.out.println("문자가 포함되어 있습니다.");
        }else {
            System.out.println("문자가 포함되어 있지 않습니다.");
        }
        
        //영문자가 있는지 검색
        if(s.matches(".*[a-zA-Z].*")) {
            System.out.println("영문자가 포함되어 있습니다.");
        }else {
            System.out.println("영문자가 포함되어 있지 않습니다.");
        }
        
        //숫자가 있는지 검색
        if(s.matches(".*[0-9].*")) {
            System.out.println("숫자가 포함되어 있습니다.");
        }else {
            System.out.println("숫자가 포함되어 있지 않습니다.");
        }

 

 

출처: [Java] 문자열에 특정 문자 포함 찾기/검색하는 다양한 방법(indexOf, contains, matches) (tistory.com)

공유하기

facebook twitter kakaoTalk kakaostory naver band