w3resource

C Programming: Replace the spaces of a string with a specific character


25. Replace Spaces with Specific Character

Write a program in C to replace the spaces in a string with a specific character.

C Programming: Replace the spaces of a string with a specific character


Sample Solution:

C Code:

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

int main() {
    int new_char;
    char t; // Variable to store the character to replace spaces
    int ctr = 0; // Counter variable
    char str[100]; // Array to store the input string

    printf("\n Replace the spaces of a string with a specific character :\n");
    printf("-------------------------------------------------------------\n");
    printf(" Input a string : ");
    fgets(str, sizeof str, stdin); // Read a string from the user including spaces
    printf(" Input replace character : ");
    scanf("%c", &t); // Read the character to replace spaces with

    printf(" After replacing the space with  %c the new string is :\n", t);
    while (str[ctr]) {
        new_char = str[ctr]; // Retrieve character from the string

        // Check if the character is a space and replace it with the specified character
        if (isspace(new_char)) {
            new_char = t;
        }

        putchar(new_char); // Print the character
        ctr++; // Move to the next character in the string
    }
    printf("\n\n");
    return 0; // Return 0 to indicate successful execution of the program
}

Output:

 Replace the spaces of a string with a specific character :
-------------------------------------------------------------
 Input a string : Be glad to see the back of
 Input replace character : *
 After replacing the space with  * the new string is :
 Be*glad*to*see*the*back*of*

Flowchart:

Flowchart: Replace the spaces of a string with a specific character


For more Practice: Solve these Related Problems:

  • Write a C program to replace every space in an input string with an asterisk (*) using a loop.
  • Write a C program to replace spaces in a string with a user-specified character, ensuring the original length is maintained.
  • Write a C program to convert multiple consecutive spaces in a string into a single specified delimiter.
  • Write a C program to change all whitespace characters in a string to hyphens (-) without using library functions.

Go to:


PREV : Check Uppercase Letter.
NEXT : Count Punctuation Characters.

C Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.