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#?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
String.TrimUsage:
If this isn’t working then it highly likely that the “spaces” aren’t spaces but some other non printing or white space character, possibly tabs. In this case you need to use the
String.Trimmethod which takes an array of characters:Source
You can add to this list as and when you come across more space like characters that are in your input data. Storing this list of characters in your database or configuration file would also mean that you don’t have to rebuild your application each time you come across a new character to check for.
NOTE
As of .NET 4
.Trim()removes any character thatChar.IsWhiteSpacereturnstruefor so it should work for most cases you come across. Given this, it’s probably not a good idea to replace this call with the one that takes a list of characters you have to maintain.It would be better to call the default
.Trim()and then call the method with your list of characters.