w3resource

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

C String: Exercise-25 with Solution

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
}

Sample 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

C Programming Code Editor:

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

Previous: Write a program in C to check whether a letter is uppercase or not.
Next: Write a program in C to count the number of punctuation characters exists in a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming-exercises/string/c-string-exercise-25.php