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, StringProgram 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
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 ;)
You may also like
- String programming exercises index.
- C program to find first occurrence of a character in a string.
- C program to find last occurrence of a character in a string.
- 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.