How do you remove all spaces from a given string and then return it?
Input = "Edpresso: Dev -Shot"
Output = "Edpresso:Dev-Shot"
non_space_count=0
variable, which will maintain the frequency of the non-space characters in a string.non_space_count
index and increase non_space_count
by 1.\0
from the final non_space_count
value until the end of the string.The time complexity of this algorithm is O(n).
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));}}