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 string static char [] removeSpacesFromString(char []str) { // 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; 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 string for (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)); } }
RELATED TAGS
CONTRIBUTOR
View all Courses