Program to Remove First Occurrence of Character in String in C
Program Description:
Write a Program to remove first occurrence of character in string in c programming language. The program will accept a string and a character from the user and searches and removes the first occurrence of the given character in the string.
📢 This Program is part of the C String Practice Programs series
We will look at different methods to Search and Remove the first occurrence of a character in the string. Each method will contain a step-by-step explanation of the program with program output. We also included the instructions to compile and run the program using your compiler.
📢The program is case-sensitive. So the Uppercase characters and Lowercase characters are different.
Let’s look at the example input and output of the program
Excepted Input and Output:
Input:
Enter a string : Learn C Programming
Enter character to remove from the string: a
Output:
String Before Removing first Occurance of character : Learn C Programming
String After Removing first Occurance of character : Lern C Programming
If you observe the output, The string’s first occurrence of the character a is removed.
Prerequisites:
We will be using the C-Strings and C-Functions. Please go through the following articles to learn more about them.
- Strings in C Language – Declare, Initialize, and Modify Strings
- Different ways to Read and Print strings in C
- Arrays in C with Example Programs
- Functions in C – How to Create and Use functions in C
We will look at the two different methods to search for the character in a string in C Language.
- Iterative Method
- User-defined Functions
Remove First Occurrence of Character in String in C Program Explanation:
Here are the step-by-step instructions for the program.
- Start the program by creating a Macro named SIZE to hold the max size of the string- #define SIZE 100
- Declare the input string( inputStr) and character to search( ch).
- Take the input string and character to search from the user and update the inputStr and ch variables respectively. We use the gets function to read the string.
- Now, To Remove the first occurrence of the character( ch) in a string( inputStr), Traverse over the input string, and find the position or index( i) of the first occurrence of the character in the string. Once we find the index( i) move all characters from the right side of the index i to one position left. ( i.e shift all characters to one place left)
- Create a Loop to find the first position of the character in input string. The For loop starts by initializing variable i to 0. It will continue looping as long as the present character (
inputStr[i]) is not a
NULLcharacter (
'\0').
- At each iteration, Check if the current character is equal( inputStr) to target character( ch). – i.e if(inputStr[i] == ch)
- If the above condition is true, Then we found the first occurrence of the character ch in the input string str. Break the loop. Otherwise, i.e condition is false, Then continue to the next iteration.
- Now the first occurrence of the character
i is stored in the index
i. Move all characters from the right side of the index
i to one position left. To do this, Create a While loop and run it till the i < strlen(inputStr) condition is
true.
- At each iteration of the while loop, Copy the character at i+1 to i – inputStr[i] = inputStr[i+1];
- Increment the i by 1. – i++;
- Once the above step 6 is completed, The first occurrence of the character ch will be removed from the input string inputStr. Display the results on the console.
- Stop the program.
Program to Remove First Occurrence of Character in String in C – Iterative Method:
Program to remove a character from the string in the c programming language.
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 40 41 42 43 44 45 46 47 48 49 50 51 52 |
/*     program to remove a character from a string in C     sillycodes.com */  #include <stdio.h> #include <string.h>  // Max Size of string #define SIZE 100  int main() {      // declare a string with 'SIZE'     char inputStr[SIZE];     char ch;     int i;      // Take the string from the user     printf("Enter a string : ");     gets(inputStr);     // Also take the search character     printf("Enter character to remove from the string: ");     scanf(" %c", &ch);      printf("String Before Removing first Occurance of character : %s \n", inputStr);      // Iterate over the string     for(i = 0; inputStr[i]; i++)     {         // check if the current character is equal to target('ch') character         if(inputStr[i] == ch)         {             // Found the character             break;         }     }      // Got the first character at index 'i'     // Move all characters from right side of 'i' to one position 'left'     while (i < strlen(inputStr))     {         // copy 'i+1' to 'i' index         inputStr[i] = inputStr[i+1];         i++;     }      printf("String After Removing first Occurance of character : %s \n", inputStr);      return 0; } |
As we are using the strlen() function, We need to include the string.h header file. If you don’t want to use the library function, Then you can look at this article, Where we implemented the custom string length (strlen) function in C.
Program Output:
Let’s compile and Run the program using your favorite compiler. We are using the GCC compiler on Ubuntu Linux.
Compile the Program.
$ gcc remove-first-character.c
The above program generates the executable file named a.out. If you are using a windows system then your executable file name will be ending with the .exe extension. Run the executable file using the following command.
1 2 3 4 5 6 |
$ ./a.out Enter a string : Learn C Programming Enter character to remove from the string: a String Before Removing first Occurance of character : Learn C Programming String After Removing first Occurance of character : Lern C Programming $ |
As we can see from the above output, The program is properly removing the first occurrence of the character from the string.
Here is another example
1 2 3 4 5 6 |
$ ./a.out Enter a string : ABBCC Enter character to remove from the string: z String Before Removing first Occurance of character : ABBCC String After Removing first Occurance of character : ABBCC $ |
If the given character( ch) is not found in the string( inputStr), Then also we are printing the message string after Removing first character. To avoid printing this, We can maintain a flag to check if the character is found in the string, and depending on the flag we can display the message.
C Program to Remove First Occurrence of Character in String using a user-defined function:
In the above method, We have written the complete program inside the main function. It is not a recommended method, Let’s rewrite the above program and use a user-defined function to remove the first occurrence of the character from the string.
By using the functions we can define a function once and can call it as many times as we want. Functions also increase the readability of the program and make it easier to debug issues. Here are the Advantages of the functions in programming.
The modified version of the program with a user-defined function.
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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
/*     program to remove a character from a string in C using functions     sillycodes.com */  #include <stdio.h> #include <string.h>  // Max Size of string #define SIZE 100  /** * @brief  - Remove the first occurance of the character from string * * @param inputStr - Input String * @param ch  - character to remove */  void removeFirstCh(char * inputStr, char ch) {     int i;      // Iterate over the string     for(i = 0; inputStr[i]; i++)     {         // check if the current character is equal to target('ch') character         if(inputStr[i] == ch)         {             // Found the character             break;         }     }      // Got the first character at index 'i'     // Move all characters from right side of 'i' to one position 'left'     while (i < strlen(inputStr))     {         // copy 'i+1' to 'i' index         inputStr[i] = inputStr[i+1];         i++;     }  }  int main() {      // declare a string with 'SIZE'     char inputStr[SIZE];     char ch;     int i;      // Take the string from the user     printf("Enter a string : ");     gets(inputStr);     // Also take the search character     printf("Enter character to remove from the string: ");     scanf(" %c", &ch);      printf("String Before Removing first Occurance of character : %s \n", inputStr);      // Call the 'removeFirstCh' with input string and character to removes     removeFirstCh(inputStr, ch);      // print the result     printf("String After Removing first Occurance of character : %s \n", inputStr);      return 0; } |
We defined a removeFirstCh() function to remove the first occurrence of the character from string. This function takes two formal arguments they are a character pointer( char *) which points to the input string( inputStr) and a character( char) which holds the character to be searched( ch).
Here is the prototype of the function.
void removeFirstCh(char * inputStr, char ch)
The removeFirstCh function removes the first occurrence of the ch from the string inputStr. We use the same logic as the above program to remove the character from the string.
Call the removeFirstCh() function from the main() function and pass the input string and the character ch.
removeFirstCh(inputStr, ch);
As the strings are passed by address/reference, Any changes made in the called function (i.e removeFirstCh) will be reflected in the main() function.
Program Output:
Compile and Run the program and observe the output.
1 2 3 4 5 6 7 |
$ gcc remove-first-func.c $ ./a.out Enter a string : Lion King Enter character to remove from the string: i String Before Removing first Occurance of character : Lion King String After Removing first Occurance of character : Lon King $ |
In this example, The input string is Lion King and the character to remove is i. The program successfully removed the first occurrence of the character i in Lion King string and returned the result as the Lon King.
Related String Practice Programs:
- C Tutorials Index
- C Programs Index
- C Program to Find Highest Frequency character in a String
- C Program to Find Lowest Frequency Character in a String
- C Program to Remove Vowels from a String
- C Program to Remove Consonants from a String
- C Program to Sort String in Ascending order
- C Program to Sort String in Descending Order
- Sort String in Ascending and Descending order using Qsort()
- C Program to Find First Occurrences of a character in a String