C program to Delete all occurrences of Character from the String.
Program : Delete all occurrences of Character from the String
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
#include<stdio.h> #include<conio.h> #include<string.h> void del(char str[], char ch); void main() { char str[10]; char ch; printf("\nEnter the string : "); gets(str); printf("\nEnter character which you want to delete : "); scanf("%ch", &ch); del(str, ch); getch(); } void del(char str[], char ch) { int i, j = 0; int size; char ch1; char str1[10]; size = strlen(str); for (i = 0; i < size; i++) { if (str[i] != ch) { ch1 = str[i]; str1[j] = ch1; j++; } } str1[j] = '\0'; printf("\ncorrected string is : %s", str1); } |
Output :
1 2 3 |
Enter the string : abhiman Enter character which you want to delete : a Corrected string is : bhimn |
Explanation :
- In this tutorial we have accepted one string from the user and character to be deleted from the user.
- Now we have passed these two parameters to function which will delete all occurrences of given character from the string.
- Whole String will be displayed as output except given Character .
Program Code Explanation :
1 2 3 4 5 6 7 8 9 |
for(i=0;i<size;i++) { if(str[i] != ch) { ch1 = str[i]; str1[j] = ch1; j++; } } |
- If character is other than given character then store it into another array.