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.
- Input string from user, store it in some variable say str.
- Input character to search from user, store it in some variable say toSearch.
- Run a loop from start till end of the string. Define a loop with structure while(str[i] != ‘\0’).
- 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 😉
Recommended posts
- String programming exercises index.
- C program to remove first occurrence of a character in a string.
- C program to remove last occurrence of a character in a string.
- C program to remove all occurrences of a character in a string.
- C program to count occurrence of a character in a given string.
- C program to find first occurrence of a word in a given string.
- C program to remove last occurrence of a word in a given string.
- C program to count frequency of each character in given string.