VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-search-a-character-in-a-string/

⇱ Program to Search a Character in a String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to Search a Character in a String

Last Updated : 25 Mar, 2025

Given a character ch and a string s, the task is to find the index of the first occurrence of the character in the string. If the character is not present in the string, return -1.

Examples:

Input: s = "geeksforgeeks", ch = 'k'
Output: 3
Explanation: The character 'k' is present at index 3 and 11 in "geeksforgeeks", but it first appears at index 3.

Input: s = "geeksforgeeks", ch = 'z'
Output: -1
Explanation: The character 'z' is not present in "geeksforgeeks".

Approach - By traversing the string - O(n) Time and O(1) Space

The idea is to traverse the input string s and for each character, check if it is equal to the character we are searching for. If we find a match, return the index of the current character.

If we reach the end of the string without finding any occurrence of the character, return -1.


Output
3

Approach - By Using in-built library functions - O(n) Time and O(1) Space

We can also use inbuilt library functions to search for a character in a string. This makes the search simple and easier to implement.


Output
3



Comment
Article Tags:
Article Tags: