• Register

In order to write a function or program ,we need to understand the problem requirement.It says that remove the first occurence of character in a string entered by user.Suppose user entered a string ‘AMAN’ and he wants to remove the first occurence of character ‘A’.After executing the function user should get string’MAN’.

Code Logic

Now we have understood the requirement of user.So how we can solve this problem?
First we will match the character which he wants to remove if it does not matche then simply increment the i for array transversal but if it matches then left shift the characters in string position by 1.That’s all we have to do.
 

Code

#include <stdio.h>
#include <string.h>
void removeFirstChar(char *str,char a);
int main(){
    char str[100];
    char a;
    printf("Enter the string:\n");
    gets(str);
    printf("Enter a character which want to remove:");
    scanf("%c",&a);
    removeFirstChar(str,a);
    printf("String after remove first occurence of character:%s",str);
    return 0;

}
void removeFirstChar(char *str,char a){
    
    int i;
    int N=strlen(str);
    while(i<N && str[i]!=a){
        i++;
    }
    while(i<N){
        str[i]=str[i+1];
        i++;
    }
    

}

Output

Enter the string:                                                                                                             
aman                                                                                                                          
Enter a character which want to remove:m                                                                                      
String after remove first occurence of character:aan 

 

100 points
5