Print the string after the specified character has occurred given no. of times in C Program


Task is to print the given after the specified character occurrence for given number of times which is specified by the user

Input : string = {“I am harsh vaid “}
   Char =’a’
   Count =2
Output : rsh vaid

It means user specified character ‘a’ and its occurrence 2 so the output string should be displayed after two occurrences of a.

Algorithm

START
Step 1 -> input character in ch(e.g. ‘a’) and count(e.g. 2) as int
Step 2 -> declare and initialize n with size of a string by sizeof(string)/sizeof(string[0])
Step 3 - > Loop For i to 0 and i<n and i++
   IF count > 0
      IF string[i]==ch
         Count=count-1
      End IF
      Continue
   End IF
   Else
      Print string[i]
   End Else
Step 4 -> End For
STOP

Example

#include <stdio.h>
int main(int argc, char const *argv[]) {
   char string[] = {"I am Harsh Vaid"};
   char ch = 'a';
   int i, count = 2;
   int n = sizeof(string)/sizeof(string[0]);
   for( i = 0; i < n; i++ ) {
      if(count>0) {
         if(string[i]==ch) {
            count--;
         }
         continue;
      }
      else
      printf("%c", string[i]);
   }
   return 0;
}

Output

If we run above program then it will generate following output

rsh Vaid
raja
Published on 08-Aug-2019 10:18:04
Advertisements