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_countvariable to0. 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 thenon_space_countindex and incrementnon_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 .
Code
#include <iostream>using namespace std;// 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";cout << string << "\n";cout << removeSpacesFromStr(string);return 0;}