C program to find the first occurrence of a character in a string

Write a C program to input any string from user and find the first occurrence of a given character in the string. How to find the first occurrence of a given character in a string in C programming. Logic to find first occurrence of a character in a string in C programming.

Example

Input

Input string: I love Codeforwin.
Input character to search: o

Output

'o' is found at index 3

Required knowledge

Basic C programming, If else, Loop, String, Functions

Logic to find first occurrence of a character in given string

Below is the step by step descriptive logic to get index of first occurrence of a character in a given string.

  1. Input string from user, store it in some variable say str.
  2. Run a loop from start character of the string to end character.
  3. Check if current character is matched with the search character. If match is found then terminate the above loop and return current character index.

Program to find first occurrence of character in string

/**
 * C program to find the first occurrence of a character in a string
 */
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size

/* Function declaration */
int indexOf(const char * str, const char toFind);


int main()
{
    char str[MAX_SIZE];
    char toFind;
    int index;

    /* Input string from user and character to be searched */
    printf("Enter any string: ");
    gets(str);
    printf("Enter character to be searched: ");
    toFind = getchar();

    index = indexOf(str, toFind);

    if(index == -1)
        printf("'%c' not found.", toFind);
    else
        printf("'%c' is found at index %d.", toFind, index);

    return 0;
}


/**
 * Returns the first index of the given character toFind in the string. 
 * If returns -1 if the given character toFind does not exists in the string.
 */
int indexOf(const char * str, const char toFind)
{
    int i = 0;

    while(str[i] != '\0')
    {
        if(str[i] == toFind)
            return i;
        i++;
    }

    // Return -1 as character not found
    return -1;
}

Note: Index returned by the function indexOf() is zero based index.

You can also use pointer based string accessing in indexOf() function. Let me re-write the above indexOf() function with pointer based string accessing instead of indexed based accessing.

int indexOf(const char * str, const char toFind)
{
    int i = 0;

    while(*str)
    {
        if(*str == toFind)
            return i;
        i++;
        str++;
    }

    // Return -1 as character not found
    return -1;
}

Read more – Program to find last occurrence of a character in a given string

Output

Enter any string: I love Codeforwin.
Enter character to be searched: o
'o' is found at index 3.

Happy coding 😉