string txt = " i am a string "
i want to remove space from start of starting and end from string'
like after that it will be "i am a string"
how i can do this in c#
string txt = " i am a string "
i want to remove space from start of starting and end from string'
like after that it will be "i am a string"
how i can do this in c#
Removes all leading and trailing white-space characters from the current String object.
Usage:
txt = txt.Trim();
UPDATE
If this isn't working then it would appear that the "spaces" aren't spaces but some other non printing character, possibly tabs. In this case you need to use the String.Trim
method which takes an array of characters:
char[] charsToTrim = { ' ', '\t' };
string result = txt.Trim(charsToTrim);
text.Trim() is to be used
string txt = " i am a string ";
txt = txt.Trim();
You can use:
Usage:
string txt = " i am a string ";
char[] charsToTrim = { ' ' };
txt = txt.Trim(charsToTrim)); // txt = "i am a string"
EDIT:
txt = txt.Replace(" ", ""); // txt = "iamastring"
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.
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.