How to remove spaces from a string in C

Problem statement

Remove all spaces from a given string and return it.

Input = "Edpresso: Dev    -Shot"
Output = "Edpresso:Dev-Shot"
1 of 4

Algorithm

  • Initialize the non_space_count=0 variable, which will maintain the frequency of the non-space characters in a string.

  • Then, go over each character in a string one by one. If a character is not a space, place it at the non_space_count index and increase non_space_count by 1.

  • Once done, place \0 at the final non_space_count value that indicates the end of the string.

Time complexity

The time complexity of this algorithm is O(n).

Implementation

#include<stdio.h>
// Funtion removing spaces from string
char * removeSpacesFromStr(char *string)
{
// non_space_count to keep the frequency of non space characters
int non_space_count = 0;
//Traverse a string and if it is non space character then, place it at index non_space_count
for (int i = 0; string[i] != '\0'; i++)
{
if (string[i] != ' ')
{
string[non_space_count] = string[i];
non_space_count++;//non_space_count incremented
}
}
//Finally placing final character at the string end
string[non_space_count] = '\0';
return string;
}
int main()
{
char string[] = "Edpresso: Dev -Shot";
printf("%s \n",string);
printf("%s",removeSpacesFromStr(string));
return 0;
}

Free Resources