Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Sort the given string using character search
Next article icon

Program to Search a Character in a String

Last Updated : 25 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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".

Table of Content

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

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.

C++
// C++ program to search a character in a string  #include <iostream> using namespace std;  // function to find the first occurrence of ch in s int findChar(string &s, char ch) {     int n = s.length();     for (int i = 0; i < n; i++) {          // If the current character is equal to ch,         // return the current index         if (s[i] == ch)             return i;     }      // If we did not find any occurrence of ch,     // return -1     return -1; }  int main() {     string s = "geeksforgeeks";     char ch = 'k';      cout << findChar(s, ch) << "\n";     return 0; } 
C
// C program to search a character in a string  #include <stdio.h> #include <string.h>  // function to find the first occurrence of ch in s int findChar(char *s, char ch) {     int n = strlen(s);     for (int i = 0; i < n; i++) {                // If the current character is equal to ch,          // return the current index         if (s[i] == ch)             return i;     }      // If we did not find any occurrence of ch,     // return -1     return -1; }  int main() {     char s[] = "geeksforgeeks";     char ch = 'k';        printf("%d\n", findChar(s, ch));     return 0; } 
Java
// Java program to search a character in a string  class GfG {        // function to find the first occurrence of ch in s     static int findChar(String s, char ch) {         int n = s.length();         for (int i = 0; i < n; i++) {                        // If the current character is equal to ch,              // return the current index             if (s.charAt(i) == ch)                 return i;         }          // If we did not find any occurrence of ch,         // return -1         return -1;     }      public static void main(String[] args) {         String s = "geeksforgeeks";         char ch = 'k';                System.out.println(findChar(s, ch));     } } 
Python
# Python program to search a character in a string  # function to find the first occurrence of ch in s def findChar(s, ch):     n = len(s)     for i in range(n):                # If the current character is equal to ch,          # return the current index         if s[i] == ch:             return i      # If we did not find any occurrence of ch,     # return -1     return -1  if __name__ == "__main__":     s = "geeksforgeeks"     ch = 'k'        print(findChar(s, ch)) 
C#
// C# program to search a character in a string  using System;  class GfG {          // function to find the first occurrence of ch in s     static int findChar(string s, char ch) {         int n = s.Length;         for (int i = 0; i < n; i++) {                        // If the current character is equal to ch,              // return the current index             if (s[i] == ch)                 return i;         }          // If we did not find any occurrence of ch,         // return -1         return -1;     }      static void Main(string[] args) {         string s = "geeksforgeeks";         char ch = 'k';          Console.WriteLine(findChar(s, ch));     } } 
JavaScript
// JavaScript program to search a character in a string  // function to find the first occurrence of ch in s function findChar(s, ch) {     let n = s.length;     for (let i = 0; i < n; i++) {                // If the current character is equal to ch,          // return the current index         if (s[i] === ch)             return i;     }      // If we did not find any occurrence of ch,     // return -1     return -1; }  let s = "geeksforgeeks"; let ch = 'k';  console.log(findChar(s, ch)); 

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.

C++
#include <iostream> #include <string>  using namespace std;  int findCharacterIndex(const string& s, char ch) {     size_t idx = s.find(ch);      if (idx != string::npos) {         return idx;     } else {         return -1;     } }  int main() {     string s = "geeksforgeeks";     char ch = 'k';      int index = findCharacterIndex(s, ch);     cout << index << endl;      return 0; } 
C
#include <stdio.h> #include <string.h>  int findCharacterIndex(const char* s, char ch) {     char* ptr = strchr(s, ch);     if (ptr != NULL) {         return ptr - s;     } else {         return -1;     } }  int main() {     const char* s = "geeksforgeeks";     char ch = 'k';      int index = findCharacterIndex(s, ch);     printf("%d\n", index);      return 0; } 
Java
public class GfG{     public static int findCharacterIndex(String s, char ch) {         int idx = s.indexOf(ch);         return (idx != -1) ? idx : -1;     }      public static void main(String[] args) {         String s = "geeksforgeeks";         char ch = 'k';          int index = findCharacterIndex(s, ch);         System.out.println(index);     } } 
Python
def find_character_index(s, ch):     idx = s.find(ch)     return idx   s = "geeksforgeeks" ch = 'k'  index = find_character_index(s, ch) print(index) 
C#
using System;  class GfG {     static int FindCharacterIndex(string s, char ch) {         int idx = s.IndexOf(ch);         return idx != -1 ? idx : -1;     }      static void Main() {         string s = "geeksforgeeks";         char ch = 'k';          int index = FindCharacterIndex(s, ch);         Console.WriteLine(index);     } } 
JavaScript
function findCharacterIndex(s, ch) {     let idx = s.indexOf(ch);     return idx !== -1 ? idx : -1; }  let s = "geeksforgeeks"; let ch = 'k';  let index = findCharacterIndex(s, ch); console.log(index); 

Output
3




Next Article
Sort the given string using character search

M

mrityuanjay8vae
Improve
Article Tags :
  • Strings
  • DSA
Practice Tags :
  • Strings

Similar Reads

  • Missing characters to make a string Pangram
    Pangram is a sentence containing every letter in the English alphabet. Given a string, find all characters that are missing from the string, i.e., the characters that can make the string a Pangram. We need to print output in alphabetic order. Examples: Input : welcome to geeksforgeeksOutput : abdhij
    8 min read
  • Searching For Characters and Substring in a String in Java
    Efficient String manipulation is very important in Java programming especially when working with text-based data. In this article, we will explore essential methods like indexOf(), contains(), and startsWith() to search characters and substrings within strings in Java. Searching for a Character in a
    5 min read
  • Convert characters of a string to opposite case
    Given a string, convert the characters of the string into the opposite case,i.e. if a character is the lower case then convert it into upper case and vice-versa. Examples: Input : geeksForgEeksOutput : GEEKSfORGeEKSInput : hello every oneOutput : HELLO EVERY ONEASCII values of alphabets: A - Z = 65
    15+ min read
  • Print the middle character of a string
    Given string str, the task is to print the middle character of a string. If the length of the string is even, then there would be two middle characters, we need to print the second middle character. Examples: Input: str = "Java"Output: vExplanation: The length of the given string is even. Therefore,
    3 min read
  • Sort the given string using character search
    Given a string str of size n. The problem is to sort the given string without using any sorting techniques (like bubble, selection, etc). The string contains only lowercase characters. Examples: Input : geeksforgeeks Output : eeeefggkkorss Input : coding Output : cdgino Algorithm: sortString(str, n)
    8 min read
  • Find last index of a character in a string
    Given a string str and a character x, find last index of x in str. Examples : Input : str = "geeks", x = 'e' Output : 2 Last index of 'e' in "geeks" is: 2 Input : str = "Hello world!", x = 'o' Output : 7 Last index of 'o' is: 7 Recommended PracticeLast index of a character in the stringTry It! Metho
    8 min read
  • Program to accept String starting with Capital letter
    Given a string str consisting of alphabets, the task is to check whether the given string is starting with a Capital Letter or Not.Examples: Input: str = "GeeksforGeeks"Output: Accepted Input: str = "geeksforgeeks"Output: Not Accepted Approach: Find the ASCII value of the first character of the stri
    3 min read
  • Program to accept Strings starting with a Vowel
    Given string str consisting of alphabets, the task is to check whether the given string is starting with a Vowel or Not. Examples: Input: str = "Animal" Output: Accepted Input: str = "GeeksforGeeks" Output: Not Accepted Approach: Find the first character of the stringCheck if the first character of
    4 min read
  • How to read or input a string?
    In this article, we are going to learn how to print or output a string using different languages. Strings are considered a data type in general and are typically represented as arrays of bytes (or words) that store a sequence of characters. Strings are defined as an array of characters.  Topics: How
    3 min read
  • Program to count vowels, consonant, digits and special characters in string.
    Given a string and the task is to count vowels, consonant, digits and special character in string. Special character also contains the white space.Examples: Input : str = "geeks for geeks121" Output : Vowels: 5 Consonant: 8 Digit: 3 Special Character: 2 Input : str = " A1 B@ d adc" Output : Vowels:
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences