How to remove any character from string in c

 In this I will tell you how to remove any character from the given String in C . So without any further delay let's get started .

Code:

#include<stdio.h>
#include<string.h>
//how to remove any character from string in c
int main(){
    char str[100];
printf("Enter the string \n");
    scanf("%[^\n]s",str);
  int j = 0;
    for(int i=0;str[i]!='\0';i++){
           if (str[i] == 'a')
        {
         str[j++]=str[i+1];  
         i++
        }
        else{
         str[j++]=str[i];
        }
        
    }
str[j]='\0';
    printf("%s  ",str);
    return 0;
}

Logic:

Now that we have see the code let's understand one by one . First of all we created a String of length 100 . And named it str . Then with the help of printf function we print user message to Enter the string . And then with help of scanf function  taking  String  as input. From the user .  And then we use a for loop and  run it till the end of the String. And we also declare variable j and initialize it from 0. For indexing of the same String after that character is removed . Then we take use   if-else  and in if condition we check for str[i]== 'a' if found then character after that is copied  in str[j++] else it copy before it is copied in str[j++]=str[i]  . And then after doing all this we end the String with '\0'.

Output:


And here you can see that our program work correctly and remove character 'a' from the String . Try this program by yourself and please provide me feedback by commenting your opinion . I hope that you find this helpful in your work. 

                                                              Thanks for reading  








No comments:

Post a Comment