SoFunction
Updated on 2025-03-07

Two ways to remove spaces in c# strings (remove spaces at both ends)

Methods to use strings:

trim(); remove spaces at both ends of strings

split(); cut

();connect

Copy the codeThe code is as follows:

class Program
    {
        static void Main(string[] args)
        {
//Original string
string str = "  hello      world, you  good world  !   ";
//Remove the spaces at both ends
           str= ();
//Cut with spaces
           string [] strArray= (new char[]{' '}, );
//Connect with spaces
           string newStr= (" ", strArray);
            (newStr);
            ();
        }
    }

Using regular methods:

Copy the codeThe code is as follows:

class Program
    {
        static void Main(string[] args)
        {
//Original string
string str = "  hello      world, you  good world  !   ";
            string s = (str, @"\s+", " ").Trim();
            (s);
            ();
        }
    }