How to remove spaces from a string in C++

String manipulation is a major element of programming. In this shot, we will learn how to remove spaces from a string in C++.

Problem statement

Remove all spaces from a given string and return it. For example:

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

Algorithm

  • Initialize the non_space_count variable to 0. This will maintain the frequency of the non-space characters in a string.

  • 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 increment 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)O(n).

Code

#include <iostream>
using namespace std;
// 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";
cout << string << "\n";
cout << removeSpacesFromStr(string);
return 0;
}

Free Resources