Javaの文字列で`indexOf()`メソッドを使って単語を見つける方法

JavaJavaBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

Introduction

In this Java programming tutorial, we will explore the indexOf() method, a versatile tool for finding words or characters within a Java String. The indexOf() method is essential for working with text in Java applications, allowing you to search for specific content within larger strings. By the end of this tutorial, you will understand how to effectively use this method and apply it in various scenarios to enhance your Java string handling skills.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/StringManipulationGroup(["String Manipulation"]) java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java/BasicSyntaxGroup -.-> java/while_loop("While Loop") java/StringManipulationGroup -.-> java/strings("Strings") java/SystemandDataProcessingGroup -.-> java/string_methods("String Methods") subgraph Lab Skills java/while_loop -.-> lab-414025{{"Javaの文字列で`indexOf()`メソッドを使って単語を見つける方法"}} java/strings -.-> lab-414025{{"Javaの文字列で`indexOf()`メソッドを使って単語を見つける方法"}} java/string_methods -.-> lab-414025{{"Javaの文字列で`indexOf()`メソッドを使って単語を見つける方法"}} end

In this step, we will create a simple Java program that demonstrates how to use the indexOf() method to find a specific word within a string.

Understanding the indexOf() Method

The indexOf() method is a built-in function in Java's String class that helps you locate the position of a substring within a larger string. Here is the basic syntax:

int indexOf(String str)

This method returns the index (position) of the first occurrence of the specified substring. If the substring is not found, the method returns -1.

Creating the Java File

Let's create our first program to see the indexOf() method in action:

  1. Open the WebIDE in your LabEx environment
  2. Create a new file by clicking on the "New File" icon or using the File menu
  3. Name the file StringSearchDemo.java
  4. Enter the following code into the file:
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");
        }
    }
}

Compiling and Running the Program

Now let's compile and run our program:

  1. Open a terminal in the WebIDE (if not already open)
  2. Compile the Java file by running:
    javac StringSearchDemo.java
  3. Run the compiled program:
    java StringSearchDemo

You should see output similar to:

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

Exploring the Result

The output shows that our program successfully found the word "fun" at position 25 in the string. In Java, string indexes start at 0, so the 26th character is at index 25.

You can verify this by counting characters: "Java programming is both " has exactly 25 characters, and then "fun" begins.

Try Searching for a Different Word

Let's modify our program to search for a different word. Change the search term from "fun" to "programming" in your code:

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

Compile and run the program again:

javac StringSearchDemo.java
java StringSearchDemo

You should now see:

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

The word "programming" starts at position 5, which is correct because "Java " has 5 characters.

Finding Multiple Occurrences of a Word

Now that we understand the basics of using indexOf() to find a single occurrence of a word, let's enhance our skills by learning how to find all occurrences of a word in a string.

Understanding the Second indexOf() Method Signature

The indexOf() method has another useful form:

int indexOf(String str, int fromIndex)

This version allows you to specify a starting position for the search. By using this form, we can find all occurrences of a word by starting each new search from where we left off.

Let's create a new Java program that finds all occurrences of a specific word:

  1. Create a new file named MultipleFinder.java
  2. Enter the following code:
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);
    }
}

Now let's compile and run our new program:

  1. In the terminal, compile the Java file:
    javac MultipleFinder.java
  2. Run the compiled program:
    java MultipleFinder

You should see output similar to:

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

How the Program Works

Let's break down how this program finds all occurrences:

  1. We set the initial search position to 0 (the beginning of the string)
  2. We enter a while loop that continues until indexOf() returns -1 (no more matches)
  3. For each match, we:
    • Print the position where we found the word
    • Update the search position to start after the current match by adding the length of the search word
  4. The loop continues until no more matches are found
  5. Finally, we print the total number of occurrences found

Handling Case Sensitivity

The indexOf() method is case-sensitive by default. Let's modify our program to perform a case-insensitive search by converting both the text and the search term to lowercase:

Add these lines to MultipleFinder.java right after the main method starts:

// 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);

Compile and run the updated program:

javac MultipleFinder.java
java MultipleFinder

The output will now include both case-sensitive and case-insensitive search results.

Building a Simple Text Analyzer

In this step, we will create a practical application that uses the indexOf() method. We'll build a simple text analyzer that can count specific words and identify their positions in a larger text.

Creating the Text Analyzer

  1. Create a new file named TextAnalyzer.java
  2. Enter the following code:
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();
            }
        }
    }
}

Compiling and Running the Text Analyzer

Now let's compile and run our text analyzer:

  1. In the terminal, compile the Java file:

    javac TextAnalyzer.java
  2. Run the compiled program:

    java TextAnalyzer
  3. When prompted, enter a word to search for, like Java

You should see output similar to:

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.

Understanding the Text Analyzer

Our text analyzer does the following:

  1. It displays a sample text for analysis
  2. It asks the user to input a word to search for
  3. It counts how many times the word appears in the text
  4. It displays the positions where the word appears
  5. For each occurrence, it shows the surrounding context
  6. It calculates what percentage of the total text is made up of the search word

This application demonstrates a practical use of the indexOf() method for text analysis. The program could be extended to include more features, such as:

  • Case-insensitive searching
  • Finding whole words only (not parts of words)
  • Analyzing multiple words at once
  • Generating statistics about the text

Try running the program again with different search words to see how it performs with various inputs.

Summary

In this tutorial, you have learned how to use the indexOf() method in Java to find words within strings. You have mastered:

  1. Using indexOf() to find the first occurrence of a word in a string
  2. Finding all occurrences of a word using a loop and the second form of indexOf()
  3. Performing case-insensitive searches by converting strings to lowercase
  4. Building a practical text analyzer application that demonstrates real-world uses of the indexOf() method

These string manipulation skills are fundamental in Java programming and will be valuable in various programming tasks, including data processing, user input validation, and text analysis. By understanding how to locate and work with specific parts of strings, you can build more sophisticated and user-friendly applications.

As you continue your Java journey, you can extend these concepts by exploring other String methods like substring(), replace(), and regular expressions for more advanced text processing.