Delete a Character from a Given String in C Programming

Introduction

In this tutorial, we will learn how to delete a character in a given string using a C program. This operation is helpful in cleaning or modifying strings based on specific character conditions. If you’re learning C programming, mastering basic string manipulation like this is essential.


C Program to Delete a Character in a Given String

#include <stdio.h>

int main() {
char str[100], ch;
int i, j;

printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

printf("Enter the character to delete: ");
scanf("%c", &ch);

for (i = 0, j = 0; str[i] != '\0'; i++) {
if (str[i] != ch) {
str[j++] = str[i];
}
}
str[j] = '\0';

printf("String after deletion: %s", str);

return 0;
}

Explanation

  • fgets() reads the full string including spaces.
  • A loop traverses the string, copying all characters except the one to be deleted.
  • The result is a new version of the string without the unwanted character.

Sample Output

Enter a string: programming
Enter the character to delete: g
String after deletion: prograamin

Use Cases

  • Removing unwanted or special characters from strings.
  • Sanitizing user inputs or logs.
  • Understanding string array manipulation and index shifting in C.

Previous Article

Replace a Character in a Given String Using C Programming

Next Article

Reverse a String Using C Programming – Simple Code with Explanation

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨