How to remove spaces from a string in C#
Problem statement
How do you remove all spaces from a given string and then return it?
Input = "Edpresso: Dev -Shot"
Output = "Edpresso:Dev-Shot"
Demo
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 the
non_space_countindex and increasenon_space_countby 1. - Once done, place
\0from the finalnon_space_countvalue until the end of the string.
Time complexity
The time complexity of this algorithm is O(n).
Code
class HelloWorld{// Funtion removing spaces from stringstatic char [] removeSpacesFromString(char []str){// 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; i < str.Length; i++)if (str[i] != ' '){str[non_space_count] = str[i];non_space_count++;//non_space_count incremented}//Finally placing final character to complete stringfor (int j = non_space_count ; j < str.Length ; j++ )str[j] = '\0';return str;}static void Main(){char []str = "Edpresso: Dev -Shot".ToCharArray();System.Console.WriteLine(str);System.Console.WriteLine(removeSpacesFromString(str));}}