C Programming Examples Tutorial Index

C String Programs

This C program removes characters from the strings given by the users. The program uses the strlen() function and loop iteration to compare and remove characters from the given string.



The program is self-explanatory and annotated as needed for understanding.

Example C Program:
#include <stdio.h>
#include <string.h> /* Header file to support string functions */

void main() {
  /* Declaration of variables used within this program. */
  char first[100], second[20];
  int i, j, fsl, ssl, temp, chk = 0;
  
  /* Take input from the user and save it to the first variable. */
  printf("Enter the String: ");
  gets(first);
  
  /* Take input from the user and save it to the second variable. */
  printf("Enter a Word: ");
  gets(second);
  
  /* Using the strlen function to calculate length of the given string. */
  fsl = strlen(first);
  ssl = strlen(second);

  /* Loop iteration to remove the second string from the first string. */
  for (i = 0; i < fsl; i++) {
    temp = i;
    for (j = 0; j < ssl; j++) {
      if (first[i] == second[j])
        i++;
    }
    chk = i - temp;
    if (chk == ssl) {
      i = temp;
      for (j = i; j < (fsl - ssl); j++)
        first[j] = first[j + ssl];
      fsl = fsl - ssl;
      first[j] = '\0';
    }
  }
  
  /*Finally, printing the result. */
  printf("\nNew String = %s", first);
}

Program Output:

Enter the String: W3 Schools
Enter a Word:  

New String = W3Schools

In the above example program, a blank space is removed from the given string.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram