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=0variable, 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 thenon_space_countindex and increasenon_space_countby 1. -
Once done, place
\0at the finalnon_space_countvalue 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 stringchar * removeSpacesFromStr(char *string){// non_space_count to keep the frequency of non space charactersint non_space_count = 0;//Traverse a string and if it is non space character then, place it at index non_space_countfor (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 endstring[non_space_count] = '\0';return string;}int main(){char string[] = "Edpresso: Dev -Shot";printf("%s \n",string);printf("%s",removeSpacesFromStr(string));return 0;}