Search with String.indexOf()
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
First character at index 0
Empty string returns -1
'e' is at index 1
Last character at index 4
'x' not found
Algorithm Flow

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.
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
class Solution {
public int solution(String s, char c) {
return s.indexOf(c);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
