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.

Example

Input

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

Must know - Program to find last occurrence of a character in given string

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;
}

Read more - Program to find first occurrence of a character in a string

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 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>