[c#] How to remove leading and trailing spaces from a string

I have the following input:

string txt = "                   i am a string                                    "

I want to remove space from start of starting and end from a string.

The result should be: "i am a string"

How can I do this in c#?

This question is related to c# string

The answer is


Use the Trim method.


You Can Use

string txt = "                   i am a string                                    ";
txt = txt.TrimStart().TrimEnd();

Output is "i am a string"


Or you can split your string to string array, splitting by space and then add every item of string array to empty string.
May be this is not the best and fastest method, but you can try, if other answer aren't what you whant.


You can use:

  • String.TrimStart - Removes all leading occurrences of a set of characters specified in an array from the current String object.
  • String.TrimEnd - Removes all trailing occurrences of a set of characters specified in an array from the current String object.
  • String.Trim - combination of the two functions above

Usage:

string txt = "                   i am a string                                    ";
char[] charsToTrim = { ' ' };    
txt = txt.Trim(charsToTrim)); // txt = "i am a string"

EDIT:

txt = txt.Replace(" ", ""); // txt = "iamastring"   

 static void Main()
    {
        // A.
        // Example strings with multiple whitespaces.
        string s1 = "He saw   a cute\tdog.";
        string s2 = "There\n\twas another sentence.";

        // B.
        // Create the Regex.
        Regex r = new Regex(@"\s+");

        // C.
        // Strip multiple spaces.
        string s3 = r.Replace(s1, @" ");
        Console.WriteLine(s3);

        // D.
        // Strip multiple spaces.
        string s4 = r.Replace(s2, @" ");
        Console.WriteLine(s4);
        Console.ReadLine();
    }

OUTPUT:

He saw a cute dog. There was another sentence. He saw a cute dog.


txt = txt.Trim();

I really don't understand some of the hoops the other answers are jumping through.

var myString = "    this    is my String ";
var newstring = myString.Trim(); // results in "this is my String"
var noSpaceString = myString.Replace(" ", ""); // results in "thisismyString";

It's not rocket science.


text.Trim() is to be used

string txt = "                   i am a string                                    ";
txt = txt.Trim();