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:
javapublic 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:
javapublic 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.
- We call the
indexOf()
method on thesentence
string, passing the search word "how" as an argument. - 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.
- 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 parameterfromIndex
, 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.
0 Comments