Skip to main content

String Operations

Searching And Indexing: indexOf(), lastIndexOf()

Learn Java string searching with indexOf() and lastIndexOf() methods. Master finding characters, substrings, and pattern matching using regular expressions. Complete guide to Java string indexing and search techniques with examples.

When working with strings in Java, you often need to search for specific characters or patterns. Java provides several methods for string searching and indexing that make this process easy. In this section, we’ll cover how to use methods like indexOf() and lastIndexOf(), how to search using regular expressions, and how to extract patterns from strings.

Searching for Characters or Substrings Using indexOf()

The indexOf() method allows you to find the position (index) of a character or substring within a string. If the character or substring is found, indexOf() returns the index (position) where it first appears. If it's not found, it returns -1.

Syntax:

int index = string.indexOf(charOrSubstring);

Example 1: Searching for a Character:

String text = "Hello, World!";
int index = text.indexOf('W');  // 7
System.out.println(index);  // Outputs: 7

In this example, 'W' is at position 7 in the string "Hello, World!". So indexOf() returns 7.

Example 2: Searching for a Substring:

String text = "Hello, World!";
int index = text.indexOf("World");  // 7
System.out.println(index);  // Outputs: 7

Here, the substring "World" starts at index 7, so indexOf() returns 7.

Example 3: When the Search Fails:

String text = "Hello, World!";
int index = text.indexOf('X');  // -1
System.out.println(index);  // Outputs: -1

Since the character 'X' is not in the string, indexOf() returns -1, indicating the search failed.

Finding the Last Occurrence Using lastIndexOf()

The lastIndexOf() method works similarly to indexOf(), but instead of finding the first occurrence of a character or substring, it finds the last occurrence.

Example 1: Finding the Last Occurrence of a Character:

String text = "Hello, Hello!";
int index = text.lastIndexOf('H');  // 7
System.out.println(index);  // Outputs: 7

In this case, the last occurrence of 'H' is at index 7.

Example 2: Finding the Last Occurrence of a Substring:

String text = "banana";
int index = text.lastIndexOf("an");  // 3
System.out.println(index);  // Outputs: 3

The substring "an" appears twice in "banana", but the last occurrence starts at index 3.

Searching Using Regular Expressions

Regular expressions (regex) are powerful for searching strings based on patterns rather than specific characters or substrings. In Java, you can use the Pattern and Matcher classes to search for patterns.

What is a Regular Expression?

A regular expression is a sequence of characters that forms a search pattern. For example, the pattern "\\d" can be used to search for any digit in a string, and "\\w+" can be used to find sequences of word characters (letters, digits, and underscores).

Example: Finding Digits in a String

import java.util.regex.*;

String text = "My phone number is 12345.";
Pattern pattern = Pattern.compile("\\d+");  // The regex \\d+ looks for one or more digits
Matcher matcher = pattern.matcher(text);

if (matcher.find()) {
    System.out.println("Found digits: " + matcher.group());  // Outputs: "12345"
}

In this example:

  • Pattern.compile("\\d+") creates a regex that looks for one or more digits.
  • matcher.find() searches for the first match of the pattern in the string.
  • matcher.group() extracts the matched part of the string (in this case, "12345").

Extracting Patterns from Strings

Once you've searched for a pattern using a regular expression, you can also extract specific parts of the string based on the match. The Matcher class provides methods like group() to access the parts of the string that match your pattern.

Example: Extracting Email Addresses:

import java.util.regex.*;

String text = "Contact us at support@example.com or sales@example.org.";
Pattern pattern = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");
Matcher matcher = pattern.matcher(text);

while (matcher.find()) {
    System.out.println("Found email: " + matcher.group());
}

In this example:

  • The regex "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}" matches a common pattern for email addresses.
  • The while (matcher.find()) loop finds and extracts all matching email addresses in the string.

Performance Considerations

While indexOf() and lastIndexOf() are very efficient for simple searches, regular expressions can be more complex and slower, especially for large strings or complicated patterns. If performance is a concern and you don't need the flexibility of regex, it's often better to stick with methods like indexOf().

Summary

  • indexOf(): Finds the first occurrence of a character or substring in a string.
  • lastIndexOf(): Finds the last occurrence of a character or substring in a string.
  • Regular Expressions (Regex): Used for more powerful and flexible searches based on patterns. You can use the Pattern and Matcher classes to search for patterns and extract parts of the string.

By learning these string searching techniques, you can easily find and extract information from strings in your Java programs!