Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
communitycreator

How to remove spaces from a string in C#

harris910

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=0 variable, 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_count index and increase non_space_count by 1.
  • Once done, place \0 from the final non_space_count value until the end of the string.

Time complexity

The time complexity of this algorithm is O(n).

Code

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

c#
communitycreator
RELATED COURSES

View all Courses

Keep Exploring