Java String 에서 indexOf() 메서드를 사용하여 단어 찾는 방법

JavaBeginner
지금 연습하기

소개

이 Java 프로그래밍 튜토리얼에서는 Java String 내에서 단어나 문자를 찾는 데 유용한 도구인 indexOf() 메서드를 살펴보겠습니다. indexOf() 메서드는 Java 애플리케이션에서 텍스트 작업을 할 때 필수적이며, 더 큰 문자열 내에서 특정 내용을 검색할 수 있게 해줍니다. 이 튜토리얼을 마치면 이 메서드를 효과적으로 사용하는 방법과 다양한 시나리오에서 Java 문자열 처리 기술을 향상시키기 위해 적용하는 방법을 이해하게 될 것입니다.

첫 번째 문자열 검색 프로그램 만들기

이 단계에서는 indexOf() 메서드를 사용하여 문자열 내에서 특정 단어를 찾는 방법을 보여주는 간단한 Java 프로그램을 만들 것입니다.

indexOf() 메서드 이해

indexOf() 메서드는 Java 의 String 클래스에 내장된 함수로, 더 큰 문자열 내에서 부분 문자열의 위치를 찾는 데 도움이 됩니다. 기본 구문은 다음과 같습니다.

int indexOf(String str)

이 메서드는 지정된 부분 문자열이 처음 나타나는 인덱스 (위치) 를 반환합니다. 부분 문자열을 찾을 수 없으면 메서드는 -1을 반환합니다.

Java 파일 만들기

indexOf() 메서드가 작동하는 것을 보기 위해 첫 번째 프로그램을 만들어 보겠습니다.

  1. LabEx 환경에서 WebIDE 를 엽니다.
  2. "New File" 아이콘을 클릭하거나 File 메뉴를 사용하여 새 파일을 만듭니다.
  3. 파일 이름을 StringSearchDemo.java로 지정합니다.
  4. 다음 코드를 파일에 입력합니다.
public class StringSearchDemo {
    public static void main(String[] args) {
        // Create a sample sentence to search through
        String sentence = "Java programming is both fun and challenging";

        // Find the position of a word using indexOf()
        int position = sentence.indexOf("fun");

        // Display the results
        System.out.println("Original sentence: " + sentence);
        System.out.println("Searching for the word 'fun'");

        if (position != -1) {
            System.out.println("The word 'fun' was found at position: " + position);
        } else {
            System.out.println("The word 'fun' was not found in the sentence");
        }
    }
}

프로그램 컴파일 및 실행

이제 프로그램을 컴파일하고 실행해 보겠습니다.

  1. WebIDE 에서 터미널을 엽니다 (아직 열려 있지 않은 경우).
  2. 다음을 실행하여 Java 파일을 컴파일합니다.
    javac StringSearchDemo.java
  3. 컴파일된 프로그램을 실행합니다.
    java StringSearchDemo

다음과 유사한 출력을 볼 수 있습니다.

Original sentence: Java programming is both fun and challenging
Searching for the word 'fun'
The word 'fun' was found at position: 25

결과 탐색

출력은 프로그램이 문자열에서 "fun"이라는 단어를 위치 25 에서 성공적으로 찾았음을 보여줍니다. Java 에서 문자열 인덱스는 0 부터 시작하므로 26 번째 문자는 인덱스 25 에 있습니다.

문자를 세어 확인할 수 있습니다. "Java programming is both "는 정확히 25 개의 문자를 가지고 있으며, 그 다음 "fun"이 시작됩니다.

다른 단어 검색 시도

다른 단어를 검색하도록 프로그램을 수정해 보겠습니다. 코드에서 검색어를 "fun"에서 "programming"으로 변경합니다.

int position = sentence.indexOf("programming");
System.out.println("Searching for the word 'programming'");

프로그램을 다시 컴파일하고 실행합니다.

javac StringSearchDemo.java
java StringSearchDemo

이제 다음을 볼 수 있습니다.

Original sentence: Java programming is both fun and challenging
Searching for the word 'programming'
The word 'programming' was found at position: 5

"programming"이라는 단어는 위치 5 에서 시작하며, "Java "가 5 개의 문자를 가지므로 올바릅니다.

단어의 여러 번 발생 찾기

이제 indexOf()를 사용하여 단일 단어의 발생을 찾는 기본 사항을 이해했으므로, 문자열에서 단어의 모든 발생을 찾는 방법을 배우면서 기술을 향상시켜 보겠습니다.

두 번째 indexOf() 메서드 시그니처 이해

indexOf() 메서드에는 또 다른 유용한 형태가 있습니다.

int indexOf(String str, int fromIndex)

이 버전은 검색 시작 위치를 지정할 수 있습니다. 이 형식을 사용하면 각 새 검색을 중단한 위치에서 시작하여 단어의 모든 발생을 찾을 수 있습니다.

다중 검색 프로그램 만들기

특정 단어의 모든 발생을 찾는 새 Java 프로그램을 만들어 보겠습니다.

  1. MultipleFinder.java라는 새 파일을 만듭니다.
  2. 다음 코드를 입력합니다.
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);
    }
}

다중 검색 프로그램 컴파일 및 실행

이제 새 프로그램을 컴파일하고 실행해 보겠습니다.

  1. 터미널에서 Java 파일을 컴파일합니다.
    javac MultipleFinder.java
  2. 컴파일된 프로그램을 실행합니다.
    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

프로그램 작동 방식

이 프로그램이 모든 발생을 찾는 방식을 자세히 살펴보겠습니다.

  1. 초기 검색 위치를 0(문자열의 시작 부분) 으로 설정합니다.
  2. indexOf()가 -1(더 이상 일치하는 항목 없음) 을 반환할 때까지 계속되는 while 루프를 입력합니다.
  3. 각 일치 항목에 대해 다음을 수행합니다.
    • 단어를 찾은 위치를 인쇄합니다.
    • 검색 단어의 길이를 더하여 현재 일치 항목 뒤에서 시작하도록 검색 위치를 업데이트합니다.
  4. 더 이상 일치하는 항목이 없을 때까지 루프가 계속됩니다.
  5. 마지막으로 찾은 총 발생 횟수를 인쇄합니다.

대소문자 구분 처리

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

이제 출력에 대소문자를 구분하는 검색 결과와 대소문자를 구분하지 않는 검색 결과가 모두 포함됩니다.

간단한 텍스트 분석기 만들기

이 단계에서는 indexOf() 메서드를 사용하는 실용적인 응용 프로그램을 만들 것입니다. 특정 단어를 세고 더 큰 텍스트에서 해당 위치를 식별할 수 있는 간단한 텍스트 분석기를 구축합니다.

텍스트 분석기 만들기

  1. TextAnalyzer.java라는 새 파일을 만듭니다.
  2. 다음 코드를 입력합니다.
import java.util.Scanner;

public class TextAnalyzer {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Sample text to analyze
        String sampleText = "Java is one of the most popular programming languages. Java was developed " +
                          "by Sun Microsystems. Today, Java is used to develop mobile apps, web applications, " +
                          "desktop applications, games and much more. Java is known for its simplicity, " +
                          "object-oriented features, and platform independence.";

        System.out.println("Text Analyzer Program");
        System.out.println("=====================");
        System.out.println("\nText to analyze:");
        System.out.println(sampleText);

        // Prompt user for a word to search
        System.out.print("\nEnter a word to search for: ");
        String searchWord = scanner.nextLine();

        // Call methods to analyze the text
        int occurrences = countOccurrences(sampleText, searchWord);

        // Display results
        System.out.println("\nAnalysis Results:");
        System.out.println("----------------");
        System.out.println("Word searched for: \"" + searchWord + "\"");
        System.out.println("Number of occurrences: " + occurrences);

        // Show the positions if the word was found
        if (occurrences > 0) {
            System.out.println("\nPositions where \"" + searchWord + "\" appears:");
            findPositions(sampleText, searchWord);
        }

        // Calculate percentage of the text the word represents
        if (occurrences > 0) {
            // Calculate what percentage of the text this word represents
            double percentage = (double)(searchWord.length() * occurrences) / sampleText.length() * 100;
            System.out.printf("\nThe word \"%s\" makes up %.2f%% of the total text.\n",
                              searchWord, percentage);
        }

        scanner.close();
    }

    // Method to count occurrences of a word in the text
    public static int countOccurrences(String text, String word) {
        int count = 0;
        int position = 0;

        while (position != -1) {
            position = text.indexOf(word, position);

            if (position != -1) {
                count++;
                position += word.length();
            }
        }

        return count;
    }

    // Method to find and print all positions of a word
    public static void findPositions(String text, String word) {
        int position = 0;
        int occurrence = 0;

        while (position != -1) {
            position = text.indexOf(word, position);

            if (position != -1) {
                occurrence++;
                System.out.println("  Occurrence " + occurrence + ": Position " + position +
                                  " (ends at position " + (position + word.length() - 1) + ")");

                // Show the context around the word
                int contextStart = Math.max(0, position - 10);
                int contextEnd = Math.min(text.length(), position + word.length() + 10);
                String context = text.substring(contextStart, contextEnd);

                // Highlight the word in the context
                System.out.print("  Context: ");
                if (contextStart > 0) {
                    System.out.print("...");
                }

                System.out.print(context);

                if (contextEnd < text.length()) {
                    System.out.print("...");
                }
                System.out.println("\n");

                position += word.length();
            }
        }
    }
}

텍스트 분석기 컴파일 및 실행

이제 텍스트 분석기를 컴파일하고 실행해 보겠습니다.

  1. 터미널에서 Java 파일을 컴파일합니다.

    javac TextAnalyzer.java
  2. 컴파일된 프로그램을 실행합니다.

    java TextAnalyzer
  3. 메시지가 표시되면 Java와 같이 검색할 단어를 입력합니다.

다음과 유사한 출력을 볼 수 있습니다.

Text Analyzer Program
=====================

Text to analyze:
Java is one of the most popular programming languages. Java was developed by Sun Microsystems. Today, Java is used to develop mobile apps, web applications, desktop applications, games and much more. Java is known for its simplicity, object-oriented features, and platform independence.

Enter a word to search for: Java

Analysis Results:
----------------
Word searched for: "Java"
Number of occurrences: 4

Positions where "Java" appears:
  Occurrence 1: Position 0 (ends at position 3)
  Context: ...Java is one o...

  Occurrence 2: Position 48 (ends at position 51)
  Context: ...guages. Java was dev...

  Occurrence 3: Position 93 (ends at position 96)
  Context: ...Today, Java is used...

  Occurrence 4: Position 197 (ends at position 200)
  Context: ...more. Java is know...

The word "Java" makes up 1.67% of the total text.

텍스트 분석기 이해

텍스트 분석기는 다음을 수행합니다.

  1. 분석할 샘플 텍스트를 표시합니다.
  2. 사용자에게 검색할 단어를 입력하라는 메시지를 표시합니다.
  3. 텍스트에서 단어가 나타나는 횟수를 계산합니다.
  4. 단어가 나타나는 위치를 표시합니다.
  5. 각 발생에 대해 주변 컨텍스트를 표시합니다.
  6. 총 텍스트에서 검색어가 차지하는 비율을 계산합니다.

이 응용 프로그램은 텍스트 분석에 indexOf() 메서드를 실용적으로 사용하는 것을 보여줍니다. 이 프로그램은 다음과 같은 더 많은 기능을 포함하도록 확장할 수 있습니다.

  • 대소문자를 구분하지 않는 검색
  • 단어의 일부가 아닌 전체 단어만 찾기
  • 여러 단어를 한 번에 분석
  • 텍스트에 대한 통계 생성

다양한 입력을 사용하여 프로그램이 어떻게 작동하는지 확인하려면 다른 검색어로 프로그램을 다시 실행해 보십시오.

요약

이 튜토리얼에서는 Java 에서 indexOf() 메서드를 사용하여 문자열 내에서 단어를 찾는 방법을 배웠습니다. 다음을 숙달했습니다.

  1. indexOf()를 사용하여 문자열에서 단어의 첫 번째 발생을 찾는 방법
  2. 루프와 indexOf()의 두 번째 형식을 사용하여 단어의 모든 발생을 찾는 방법
  3. 문자열을 소문자로 변환하여 대소문자를 구분하지 않는 검색을 수행하는 방법
  4. indexOf() 메서드의 실제 사용을 보여주는 실용적인 텍스트 분석기 응용 프로그램 구축

이러한 문자열 조작 기술은 Java 프로그래밍의 기본이며 데이터 처리, 사용자 입력 유효성 검사 및 텍스트 분석을 포함한 다양한 프로그래밍 작업에 유용합니다. 문자열의 특정 부분을 찾고 작업하는 방법을 이해함으로써 더 정교하고 사용자 친화적인 응용 프로그램을 구축할 수 있습니다.

Java 여정을 계속 진행하면서 더 발전된 텍스트 처리를 위해 substring(), replace() 및 정규 표현식과 같은 다른 String 메서드를 탐색하여 이러한 개념을 확장할 수 있습니다.