English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
이 예제에서는 Java의 contains()와 indexOf() 메서드를 사용하여 문자열이 서브 문자열을 포함하는지 확인하는 방법을 배웁니다.
이 예제를 이해하려면 다음을 이해해야 합니다Java 프로그래밍주제:
class Main { public static void main(String[] args) { //문자열을 생성하십시오 String txt = "This is w"3codebox"; String str1 = "w3codebox"; String str2 = "Programming"; //txt에 이름이 존재하는지 확인 //contains()를 사용하여 boolean result = txt.contains(str1); if(result) { System.out.println(str1 + "이 문자열이 문자열에 있습니다."); } else { System.out.println(str1 + "이 문자열이 없습니다."); } result = txt.contains(str2); if(result) { System.out.println(str2 + "이 문자열이 문자열에 있습니다."); } else { System.out.println(str2 + "이 문자열이 없습니다."); } } }
출력 결과
w3codebox 문자열이 문자열에 있습니다. Programming 문자열이 문자열에 없습니다.
위의 예제에서 우리는 txt, str이라는 세 개의 문자열을 가지고 있습니다1와 str2。여기서는 String의contains()문자열 str을 확인하는 메서드1와 str2txt에 나타나는지 확인합니다。
class Main { public static void main(String[] args) { //문자열을 생성하십시오 String txt = "This is w"3codebox"; String str1 = "w3codebox"; String str2 = "Programming"; //str을 확인합니다1txt에 존재하는지 확인합니다 //using indexOf() int result = txt.indexOf(str1); if(result == -1) { System.out.println(str1 + "이 문자열이 없습니다."); } else { System.out.println(str1 + "이 문자열이 문자열에 있습니다."); } //str을 확인합니다2txt에 존재하는지 확인합니다 //using indexOf() result = txt.indexOf(str2); if(result == -1) { System.out.println(str2 + "이 문자열이 없습니다."); } else { System.out.println(str2 + "이 문자열이 문자열에 있습니다."); } } }
출력 결과
w3codebox 문자열이 문자열에 있습니다. Programming 문자열이 문자열에 없습니다.
이 예제에서는String의 indexOf()메서드를 사용하여 문자열 str을 찾습니다1와 str2txt 파일 내 위치에서. 문자열이 발견되면 문자열의 위치를 반환합니다. 발견되지 않으면-1。