Friday, January 24, 2025
HomeProgrammingJava String indexOf() Method

Java String indexOf() Method

The indexOf() method in Java is used to find the index of the first occurrence of a character or a substring within a string. If the character or substring is not found, it returns -1.

Syntax

  1. For a character:
    int indexOf(int ch)
    
    • ch: The character to search for.
    • Returns the index of the first occurrence of the character ch, or -1 if it’s not found.
  2. For a substring:
    int indexOf(String str)
    
    • str: The substring to search for.
    • Returns the index of the first occurrence of the substring str, or -1 if it’s not found.
  3. With a starting index:
    int indexOf(int ch, int fromIndex)
    
    • ch: The character to search for.
    • fromIndex: The index from which to start searching.
    • Returns the index of the first occurrence of ch after the specified fromIndex, or -1 if it’s not found.
  4. For a substring with starting index:
    int indexOf(String str, int fromIndex)
    
    • str: The substring to search for.
    • fromIndex: The index from which to start searching.
    • Returns the index of the first occurrence of str after the specified fromIndex, or -1 if it’s not found.
See also  Java Operator Precedence

Example Usage

public class Example {
    public static void main(String[] args) {
        String str = "Hello, world!";
        
        // Searching for a character
        int index1 = str.indexOf('o');  // Returns 4
        System.out.println("Index of 'o': " + index1);
        
        // Searching for a substring
        int index2 = str.indexOf("world");  // Returns 7
        System.out.println("Index of 'world': " + index2);
        
        // Searching for a character starting from index 5
        int index3 = str.indexOf('o', 5);  // Returns 8
        System.out.println("Index of 'o' starting from index 5: " + index3);
        
        // Searching for a substring starting from index 5
        int index4 = str.indexOf("world", 5);  // Returns 7
        System.out.println("Index of 'world' starting from index 5: " + index4);
    }
}

Key Points:

  • If the character or substring is not found, -1 is returned.
  • The search is case-sensitive.
  • The method can also take a starting index to specify from where to begin the search.
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x