C Program to Replace a Character in a String

C Program to Replace a Character in a String

Replacing characters in a string is a common operation in programming. It is useful for tasks such as data cleaning, text formatting, or implementing simple encryption. In C, strings are arrays of characters ending with a null terminator (\0). By scanning the string and changing specific characters, you can modify text as needed.

In this tutorial, we will learn how to replace a specific character in a string with another character. We will explore multiple approaches including using loops and pointers. Each example will be explained carefully so that you understand how character replacement works in memory.

Understanding the Problem

Given a string, a target character to replace, and a new character, the goal is to update the string so that every occurrence of the target character is replaced with the new character.

For example, if the string is "programming" and we want to replace 'g' with 'x', the resulting string should be "proxramminx".

The basic steps are:

  1. Traverse the string character by character.
  2. Check if the current character matches the target.
  3. If it matches, assign the new character to that position.

This operation is simple but teaches fundamental concepts of string traversal and modification in C.

Program 1: Using a Loop

A loop is the most basic way to replace characters. It checks each character and updates it if it matches the target. This method is easy to learn and widely used.

#include <stdio.h>
#include <string.h>

int main() {

    char str[100];
    char target, replacement;

    // Get string input from user
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    str[strcspn(str, "\n")] = '\0';  // remove newline character

    // Get target and replacement characters
    printf("Enter character to replace: ");
    scanf("%c", &target);

    getchar(); // clear leftover newline

    printf("Enter replacement character: ");
    scanf("%c", &replacement);

    // Traverse the string and replace matches
    for (int i = 0; str[i] != '\0'; i++) {

        if (str[i] == target) {
            str[i] = replacement;
        }

    }

    printf("Updated string: %s\n", str);

    return 0;

}

This method is reliable because it explicitly checks every character. It is best for simple programs where performance is not the main concern. You can always expand it later to handle more complex situations.

Program 2: Using Pointers

Instead of array indices, you can use pointers to traverse the string. Pointers move through memory directly, updating characters as needed. This method is efficient and flexible.

#include <stdio.h>
#include <string.h>

int main() {

    char str[100], *ptr;
    char target, replacement;

    // Get string input from user
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    str[strcspn(str, "\n")] = '\0'; // remove newline character

    // Get target and replacement characters
    printf("Enter character to replace: ");
    scanf("%c", &target);

    getchar(); // clear leftover newline

    printf("Enter replacement character: ");
    scanf("%c", &replacement);

    // Use pointer to walk through the string
    for (ptr = str; *ptr != '\0'; ptr++) {

        if (*ptr == target) {
            *ptr = replacement;
        }

    }

    printf("Updated string: %s\n", str);

    return 0;

}

The pointer method is powerful and efficient. It teaches how strings really behave in memory. While it might seem harder at first, it becomes second nature with practice.

Program 3: Case-Insensitive Replacement

Sometimes, letter case should not matter. By using tolower() or toupper() from <ctype.h>, you can compare characters in a case-insensitive way. This makes replacements more flexible.

#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main() {

    char str[100];
    char target, replacement;

    // Get string input from user
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    str[strcspn(str, "\n")] = '\0'; // remove newline character

    // Get target and replacement characters
    printf("Enter character to replace: ");
    scanf("%c", &target);

    getchar(); // clear leftover newline

    printf("Enter replacement character: ");
    scanf("%c", &replacement);

    // Replace case-insensitive matches
    for (int i = 0; str[i] != '\0'; i++) {

        if (tolower(str[i]) == tolower(target)) {
            str[i] = replacement;
        }

    }

    printf("Updated string (case-insensitive): %s\n", str);

    return 0;

}

This program is excellent when handling user input where letter case varies. It prevents mismatches and ensures smoother interaction. The trade-off is slightly more processing per character, but that is rarely an issue.

Program 4: Using a Function

Placing the replacement logic inside a function makes the code cleaner. It separates the task from the main program, improving readability. Functions also make the code reusable.

#include <stdio.h>
#include <string.h>

// Function to replace characters in a string
void replaceChar(char *str, char target, char replacement) {

    // Traverse the string and replace matches
    for (int i = 0; str[i] != '\0'; i++) {

        if (str[i] == target) {
            str[i] = replacement;
        }

    }

}

int main() {

    char str[100];
    char target, replacement;

    // Get string input from user
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    str[strcspn(str, "\n")] = '\0'; // remove newline character

    // Get target and replacement characters
    printf("Enter character to replace: ");
    scanf("%c", &target);

    getchar(); // clear leftover newline

    printf("Enter replacement character: ");
    scanf("%c", &replacement);

    // Call function
    replaceChar(str, target, replacement);

    printf("Updated string (via function): %s\n", str);

    return 0;

}

Using a function is a clean design choice. It keeps programs well-structured and easy to expand. Beginners also benefit from learning modular programming.

Program 5: Using strchr()

The strchr() function finds the first occurrence of a character in a string. By looping with it, you can replace all matches without manually checking each character.

#include <stdio.h>
#include <string.h>

int main() {

    char str[100];
    char target, replacement;
    char *pos;

    // Get string input from user
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    str[strcspn(str, "\n")] = '\0'; // remove newline character

    // Get target and replacement characters
    printf("Enter character to replace: ");
    scanf("%c", &target);

    getchar(); // clear leftover newline

    printf("Enter replacement character: ");
    scanf("%c", &replacement);

    // Use strchr to locate characters
    pos = strchr(str, target);

    while (pos != NULL) {

        *pos = replacement;
        pos = strchr(pos + 1, target); // continue searching

    }

    printf("Updated string (using strchr): %s\n", str);

    return 0;

}

This approach shows the value of combining your logic with C’s standard library. It is clean and effective. It also demonstrates a professional way of writing code.

Program 6: Recursion

Recursion processes one character at a time and calls itself for the rest of the string. It avoids loops and makes the code look elegant. This method works best for short strings.

#include <stdio.h>
#include <string.h>

// Recursive function for replacement
void replaceCharRecursive(char *str, char target, char replacement) {

    if (*str == '\0') return; // base case

    if (*str == target) {
        *str = replacement;
    }

    replaceCharRecursive(str + 1, target, replacement); // recursive step

}

int main() {

    char str[100];
    char target, replacement;

    // Get string input from user
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    str[strcspn(str, "\n")] = '\0'; // remove newline character

    // Get target and replacement characters
    printf("Enter character to replace: ");
    scanf("%c", &target);

    getchar(); // clear leftover newline

    printf("Enter replacement character: ");
    scanf("%c", &replacement);

    // Call recursive function
    replaceCharRecursive(str, target, replacement);

    printf("Updated string (recursion): %s\n", str);

    return 0;

}

This approach is best suited for small strings and learning purposes. It gives a fresh perspective but should be avoided in performance-critical code.

Program 7: Recursion with strchr()

By combining recursion with strchr(), you can make the code concise. strchr() finds the next match, and recursion continues from there. This creates a short and expressive solution.

#include <stdio.h>
#include <string.h>

// Recursive function using strchr
void replaceRecursiveStrchr(char *str, char target, char replacement) {

    char *pos = strchr(str, target);

    if (pos == NULL) return; // base case

    *pos = replacement;
    replaceRecursiveStrchr(pos + 1, target, replacement); // continue after match

}

int main() {

    char str[100];
    char target, replacement;

    // Get string input from user
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    str[strcspn(str, "\n")] = '\0'; // remove newline character

    // Get target and replacement characters
    printf("Enter character to replace: ");
    scanf("%c", &target);

    getchar(); // clear leftover newline

    printf("Enter replacement character: ");
    scanf("%c", &replacement);

    // Call recursive strchr function
    replaceRecursiveStrchr(str, target, replacement);

    printf("Updated string (recursion + strchr): %s\n", str);

    return 0;

}

This method is short, expressive, and elegant. It is a good example of combining standard functions with recursion. It is especially useful for those who enjoy concise solutions.

Program 8: Creating a New String

Instead of changing the original string, you can build a new one. Each character is copied, and replacements are applied only when needed. This keeps the original intact.

#include <stdio.h>
#include <string.h>

int main() {

    char str[100], newStr[100];
    char target, replacement;
    int i, j = 0;

    // Get string input from user
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    str[strcspn(str, "\n")] = '\0'; // remove newline character

    // Get target and replacement characters
    printf("Enter character to replace: ");
    scanf("%c", &target);

    getchar(); // clear leftover newline

    printf("Enter replacement character: ");
    scanf("%c", &replacement);

    // Copy characters into new string
    for (i = 0; str[i] != '\0'; i++) {

        if (str[i] == target) {
            newStr[j++] = replacement;
        } else {
            newStr[j++] = str[i];
        }

    }

    newStr[j] = '\0'; // null-terminate new string

    printf("Original string: %s\n", str);
    printf("New string (unchanged original): %s\n", newStr);

    return 0;

}

This is the safest approach when the original data must be kept intact. It costs more memory, but it avoids accidental data loss. It is especially useful in complex applications.

FAQs

1. Can this program replace multiple occurrences of a character?
Yes, it will replace every occurrence of the target character in the string.

2. Can I replace a character only once?
Yes, you can modify the loop to stop after the first replacement using a break statement.

3. What if the target character does not exist in the string?
The string remains unchanged, and no error occurs.

4. Can this handle special characters and spaces?
Yes, any character, including spaces, punctuation, and digits, can be replaced.

Conclusion

Replacing characters in a string is a fundamental operation in C programming. By using loops, pointers, and optional case-insensitive logic, you can efficiently update strings to meet your requirements.

We explored three methods: using loops, using pointers, and performing case-insensitive replacement. Mastering these techniques prepares you for more advanced string manipulations such as find-and-replace, formatting, and text processing.

References & Additional Resources

A curated set of books, tutorials, and documentation for learning string replacement, pointers, and character functions in C.

  1. Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language, 2nd Edition, Prentice Hall, 1988 – Classic textbook covering C fundamentals including strings, arrays, and pointers.
  2. GeeksforGeeks: Replace a Character in C – Step-by-step guide on replacing characters in strings.
  3. Tutorialspoint: C Strings – Overview of string declaration, initialization, and handling in C.
  4. Cprogramming.com: Pointers in C – Explains pointer concepts and their role in string manipulation.
  5. cplusplus.com: ctype.h Functions – Reference for character-handling functions such as toupper(), tolower(), and classification functions.
Scroll to Top