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. Logic to search all occurrences of a character in given string in C program.

Required knowledge

Basic C programming, C for loop, Array, functions, Strings

Logic to search occurrences of a character in given string

Below is the step by step descriptive logic to find all occurrences of a character in given string.

  1. Input string from user, store it in some variable say str.
  2. Input character to search from user, store it in some variable say toSearch.
  3. Run a loop from start till end of the string. Define a loop with structure while(str[i] != '\0').
  4. Inside the loop, if current character of str equal to toSearch, then print the current string index.

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 string size 

int main()
{
    char str[MAX_SIZE];
    char toSearch;
    int i;

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

    /* Run loop till the last character of string */
    i=0;
    while(str[i]!='\0')
    {
        /* If character is found in string */
        if(str[i] == toSearch)
        {
            printf("'%c' is found at index %d\n", toSearch, i);
        }

        i++;
    }

    return 0;
}



Output:

Enter any string: I love c programcoding
Enter any character to search: o
'o' is found at index 3
'o' is found at index 11
'o' is found at index 17
Process returned 0 (0x0) execution time : 47.444 s



Instagram