String Exercises
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.
- 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; }