Ticker

6/recent/ticker-posts

String indexOf() Method in Java

String indexOf() Method in Java

Introduction:

The indexOf() method in Java is used to find the index of the first occurrence of a specified substring within a given string. It returns the index of the first character of the substring if found; otherwise, it returns -1. The index is 0-based, which means the first character in the string has an index of 0.

Syntax:

java
public int indexOf(String str)

Parameters:

  • str: The substring to search for in the given string.

Return Value:

  • An integer value representing the index of the first occurrence of the substring if found; otherwise, it returns -1.

Example:

java
public class IndexOfExample {
public static void main(String[] args) {
String sentence = "Hello, how are you doing?";
String searchWord = "how";

int index = sentence.indexOf(searchWord);

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

Explanation:

In the given example, we have a string sentence containing the value "Hello, how are you doing?", and we want to find the index of the word "how" within this sentence.

  1. We call the indexOf() method on the sentence string, passing the search word "how" as an argument.
  2. The method searches for the first occurrence of "how" in the string and returns the index value, which is 7 in this case, as "h" appears at index 7 in the sentence.
  3. We then check if the returned index is not -1 (indicating that the word is found). If it is not -1, we print the message indicating the index where the word is found. Otherwise, we print a message saying that the word is not present in the sentence.

Additional Notes:

  • The indexOf() method has an overloaded version that takes an additional parameter fromIndex, which specifies the starting index for the search. If provided, the method searches for the substring after the specified index.
  • If the search word occurs multiple times in the string, the method will return the index of the first occurrence. For finding all occurrences, you can use a loop or other appropriate methods.

Post a Comment

0 Comments