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.

Example:
Input string: I love programming.
Input character: o
Output: 3

Required knowledge

Basic C programming, If else, Loop, String

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


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



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

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

    index = indexOf(text, toFind);

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

    return 0;
}


/**
 * Finds the first index of the given character toFind in the string text.
 */
int indexOf(const char * text, const char toFind)
{
    int index = -1;
    int i, len;

    len = strlen(text);

    for(i=0; i<len; i++)
    {
        if(text[i] == toFind)
        {
            index = i;
            break;
        }
    }

    return index;
} 


Output
Enter any string: I love programming.
Enter character to be searched: o
Index of 'o' is 3.


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


Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment