Latest :

C Program To Search All Occurrences Of A Character In String | C Programs

C program to search all occurrences of a character in a given string – In this article, we will explain the multitude of ways to search all occurrences of a character in a given string in C programming.

Suitable examples and sample programs have also been added so that you can understand the whole thing very clearly. The compiler has also been added with which you can execute it yourself.

The ways used in this piece are as follows:

  • Using Standard Method
  • Using Function
  • Using Recursion

A string is nothing but an array of characters. The value of a string is determined by the terminating character. Its value is considered to be 0.

C Program To Search All Occurrences Of A Character In String

As you can see given in the image above, firstly, you need to enter a particular string.

The string entered here is as follows:

“Keep your eyes on the stars and your feet on the ground”

The, enter the character that you want to be searched.

The character ‘e’ is chosen in this case for the entered string.

Hence, after observation, it is seen that the character ‘e’ is found at the locations:

  • 1
  • 2
  • 10
  • 12
  • 20
  • 38
  • 39
  • 47

Thus, the multiple ways to do the same in C programming are as follows:

Using Standard Method

  1. Read the entered string and store that string in the variable s using gets(s).

2) Read the entered character to be searched using getchar() and store the character into the variable c.

3) The for loop iterates through the string from i=0 to end of the string.

a) If the character at the variable c match with s[i] then print the location of the character where it found in the string.

b) Increase the i value to go through the next element of the string.

Output:

Using Function

  1. The main() calls the check(char *s, char c) function by passing the string, character as arguments to the function.

2) The function prints all occurrences of the character in the string.

a) Compare the given character with each element of the given string using the for loop with the structure for(i=0;s[i];i++).

b) If the character matches with the element of the string s[i], then print location of the string i. Otherwise, go through the next element of the string.

Output:

Using Recursion

  1. The check(char *s, char c) function calls itself recursively until the character at s[i] becomes null.

2) If the s[i] of the string is not null then compare the character with s[i].

a) If both are equal then print the location of the character i.e ‘i’.

b) Increase the i value.

c) The function calls itself.

Output:

x

Check Also

C Program To Find Reverse Of An Array – C Programs

C program to find the reverse of an array – In this article, we will ...