C program to search all occurrences of a character in a string

Write a C program to search all occurrences of a character in a string using loop. How to find all occurrences of a character in a given string using for loop in C programming. Program to print all index of a character in a given string.

Example:
Input string: I love programming. I love CodeforWin.
Input character to search: o
Output 'o' found at index: 3, 9, 23, 28, 32

Required knowledge

Basic C programming, Loop, String

Program to search occurrence of character in string

/**
 * C program to search all occurrences of a character in a string
 */

#include <stdio.h>

#define MAX_SIZE 100 //Maximum size of the string

int main()
{
    char string[MAX_SIZE];
    char search;
    int i;

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

    //Runs a loop till the NULL character is found
    for(i=0; string[i]!='\0'; i++)
    {
        /*
         * If character is found in string
         */
        if(string[i] == search)
        {
            printf("'%c' is found at index %d\n", search, i);
        }
    }

    return 0;
}


Output
Enter any string: I love programming. I love CodeforWin.
Enter any character to search: o
'o' is found at index 3
'o' is found at index 9
'o' is found at index 23
'o' is found at index 28
'o' is found at index 32

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