단어의 여러 번 발생 찾기
이제 indexOf()를 사용하여 단일 단어의 발생을 찾는 기본 사항을 이해했으므로, 문자열에서 단어의 모든 발생을 찾는 방법을 배우면서 기술을 향상시켜 보겠습니다.
두 번째 indexOf() 메서드 시그니처 이해
indexOf() 메서드에는 또 다른 유용한 형태가 있습니다.
int indexOf(String str, int fromIndex)
이 버전은 검색 시작 위치를 지정할 수 있습니다. 이 형식을 사용하면 각 새 검색을 중단한 위치에서 시작하여 단어의 모든 발생을 찾을 수 있습니다.
다중 검색 프로그램 만들기
특정 단어의 모든 발생을 찾는 새 Java 프로그램을 만들어 보겠습니다.
MultipleFinder.java라는 새 파일을 만듭니다.
- 다음 코드를 입력합니다.
public class MultipleFinder {
public static void main(String[] args) {
// Create a sample text with multiple occurrences of a word
String paragraph = "Java is a popular programming language. Java runs on various platforms. " +
"Java is used for developing web applications, mobile apps, and more. " +
"Learning Java is essential for many software development roles.";
System.out.println("Original text:");
System.out.println(paragraph);
System.out.println("\nSearching for all occurrences of 'Java':");
// Find all occurrences of "Java"
String searchWord = "Java";
int position = 0;
int count = 0;
// Loop until no more occurrences are found
while (position != -1) {
position = paragraph.indexOf(searchWord, position);
if (position != -1) {
count++;
System.out.println("Occurrence " + count + " found at position: " + position);
// Move past this occurrence to find the next one
position += searchWord.length();
}
}
System.out.println("\nTotal occurrences found: " + count);
}
}
다중 검색 프로그램 컴파일 및 실행
이제 새 프로그램을 컴파일하고 실행해 보겠습니다.
- 터미널에서 Java 파일을 컴파일합니다.
javac MultipleFinder.java
- 컴파일된 프로그램을 실행합니다.
java MultipleFinder
다음과 유사한 출력을 볼 수 있습니다.
Original text:
Java is a popular programming language. Java runs on various platforms. Java is used for developing web applications, mobile apps, and more. Learning Java is essential for many software development roles.
Searching for all occurrences of 'Java':
Occurrence 1 found at position: 0
Occurrence 2 found at position: 42
Occurrence 3 found at position: 72
Occurrence 4 found at position: 149
Total occurrences found: 4
프로그램 작동 방식
이 프로그램이 모든 발생을 찾는 방식을 자세히 살펴보겠습니다.
- 초기 검색 위치를 0(문자열의 시작 부분) 으로 설정합니다.
indexOf()가 -1(더 이상 일치하는 항목 없음) 을 반환할 때까지 계속되는 while 루프를 입력합니다.
- 각 일치 항목에 대해 다음을 수행합니다.
- 단어를 찾은 위치를 인쇄합니다.
- 검색 단어의 길이를 더하여 현재 일치 항목 뒤에서 시작하도록 검색 위치를 업데이트합니다.
- 더 이상 일치하는 항목이 없을 때까지 루프가 계속됩니다.
- 마지막으로 찾은 총 발생 횟수를 인쇄합니다.
대소문자 구분 처리
indexOf() 메서드는 기본적으로 대소문자를 구분합니다. 텍스트와 검색어를 모두 소문자로 변환하여 대소문자를 구분하지 않는 검색을 수행하도록 프로그램을 수정해 보겠습니다.
MultipleFinder.java에 main 메서드가 시작된 직후 다음 줄을 추가합니다.
// Case-insensitive search demonstration
System.out.println("\n--- Case-insensitive search ---");
String lowercaseParagraph = paragraph.toLowerCase();
String lowercaseSearchWord = searchWord.toLowerCase();
position = 0;
count = 0;
while (position != -1) {
position = lowercaseParagraph.indexOf(lowercaseSearchWord, position);
if (position != -1) {
count++;
System.out.println("Occurrence " + count + " found at position: " + position);
position += lowercaseSearchWord.length();
}
}
System.out.println("\nTotal occurrences found (case-insensitive): " + count);
업데이트된 프로그램을 컴파일하고 실행합니다.
javac MultipleFinder.java
java MultipleFinder
이제 출력에 대소문자를 구분하는 검색 결과와 대소문자를 구분하지 않는 검색 결과가 모두 포함됩니다.