Delete a Character from a Given String in C

Written: August 15, 2026

Deleting characters in C means rewriting the string without library erase helpers—perfect pointer/index practice.

This walkthrough keeps the logic small and readable so you can type it, run it, and then change one input at a time to see what happens.

What you will build

Walk the string with a read index and a write index; copy only characters that should stay, then terminate with ‘\0’.

  • Read a string and a character to delete
  • Scan with i (read) and j (write)
  • Copy s[i] to s[j] when it is not the target
  • Write the final null terminator at s[j]

Working C example

include <stdio.h>

void delete_char(char s, char ch) {
    int i, j = 0;
    for (i = 0; s[i] != '\0'; i++) {
        if (s[i] != ch) {
            s[j++] = s[i];
        }
    }
    s[j] = '\0';
}

int main(void) {
    char s[200], ch;
    printf("Enter string: ");
    if (!fgets(s, sizeof s, stdin)) return 1;
    / strip newline if present /
    for (int k = 0; s[k]; k++) if (s[k] == '\n') s[k] = '\0';
    printf("Character to delete: ");
    if (scanf(" %c", &ch) != 1) return 1;
    delete_char(s, ch);
    printf("Result: %s\n", s);
    return 0;
}

Advertisement

How the logic works

Read the program top to bottom: includes and main first, then the statements that change variables, then the print that proves the result.

If your output looks wrong, print the variables before and after the critical lines. That single habit catches most beginner bugs faster than rewriting the whole file.

Test deleting a character that does not exist and deleting every character—both should leave a valid (possibly empty) string.

Advertisement

Keep learning

If this walkthrough on Delete a Character from a Given String in C helped, open the code again and change one input or assumption. Small experiments beat rereading the same example.

Want more step-by-step tutorials like this? Browse blog.xqa.io — and tell us which topic you want next.

Advertisement

Previous Article

Stack Implementation in C Using an Array

Next Article

Introduction to Pointers in C: Call by Value vs Call by Reference

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 ✨