C program to replace the string space with a given character

In this tutorial we will learn writing the C program to replace the spaces from the string with given character. This program is little bit logical. Here we have to find the available space in the input string and then replace that space with the given character by user.

How string space replacement with character program work?

  • This program will take a String as an input. Also program will take one character to replace with space.
  • Now we will find the spaces available in the string using if check. And if space found then replace with given character.
  • String is an array of character, so we can easily iterate the string using for loop and compare with the space. And if space found then replace with this index with the character given as an input by the user.

C Program to replace space of String with user given character

#include<stdio.h>
#include<string.h>
void replaceSpace(char *str, char charToReplace) {
    char c;
    int i;
    int len = strlen(str);
    for(i=0; i<len; i++)
    {
        if(str[i] == ' ')
        {
            str[i] = charToReplace;

        }
    }
}

int main() {
    char str[100],ch;
    int i,j,len;
    printf("Enter the string : \n");
    fgets(str, 100, stdin);
    printf("Enter a char you want to replace with space : ");
    scanf("%c",&ch);
    replaceSpace(str,ch);
    printf("String after removing ' ' String Become: \n %s", str);
    return 0;
}

Output :

Enter the string : 
Quescol is website
Enter a char you want to replace with space : T
String after removing ' ' String Become: 
 QuescolTisTwebsite


[wpusb]