Code Logo

Search with String.indexOf()

Published at25 Jul 2026
Java OOP Easy 2 views
Like0

Write a Java function that takes a string and a character, and returns the index of the first occurrence of the character in the string using indexOf(). If the character is not found, return -1.

String.indexOf() is a method that returns the index within the string of the first occurrence of a specified character or substring. There are four overloaded versions: indexOf(int ch), indexOf(int ch, int fromIndex), indexOf(String str), and indexOf(String str, int fromIndex). All return -1 if not found.

The indexOf() method performs a linear search from the beginning (or from the specified fromIndex). For characters, the parameter is an int representing the Unicode code point. The method is case-sensitive and is the standard way to search within strings in Java.

Time complexity is O(n) where n is the string length. Space complexity is O(1). The method searches from left to right and returns the first match. Use lastIndexOf() to search from right to left.

Edge cases include empty strings (returns -1 for any search), character not present (returns -1), character at the beginning (returns 0), and searching for an empty string (returns 0 per Java specification).

Example Input & Output

Example 1
Input
"hello",h
Output
0
Explanation

First character at index 0

Example 2
Input
"",a
Output
-1
Explanation

Empty string returns -1

Example 3
Input
"hello",e
Output
1
Explanation

'e' is at index 1

Example 4
Input
"hello",o
Output
4
Explanation

Last character at index 4

Example 5
Input
"hello",x
Output
-1
Explanation

'x' not found

Algorithm Flow

Recommendation Algorithm Flow for Search with String.indexOf()
Recommendation Algorithm Flow for Search with String.indexOf()

Solution Approach

Find the first occurrence of a character or substring within a string using indexOf(). This method returns the index of the first match or -1 if not found. An optional second parameter specifies the starting position for the search.

class Solution { public int solution(String s, char c) { return s.indexOf(c); } }

indexOf() is overloaded: indexOf(int ch) for characters, indexOf(String str) for substrings. For last occurrence, use lastIndexOf(). Both are case-sensitive.

Time O(n), Space O(1).

Best Answers

java - Approach 1
class Solution {
    public int solution(String s, char c) {
        return s.indexOf(c);
    }
}