C# Trim string regardless of characters

2020-04-21 06:31发布

So here the situation.

I have multiple strings that begin and end with a random amount of spaces. The problem is the string contains multiple words so I can't just replace(" ","") so for example.

"       apple red "
'   orange orange   '  
'  pear grapes  '  
'                   turnship turn it over here '  

and I would want to return.
'apple red'
'orange orange'
'pear grapes'
'turnship turn it over here '

标签: c#
4条回答
▲ chillily
2楼-- · 2020-04-21 07:01

Try

yourString.Trim();

Removes all occurrences of white space characters from the beginning and end of this instance.

[Visual Basic] Overloads Public Function Trim() As String [C#] public string Trim(); [C++] public: String* Trim(); [JScript] public function Trim() : String; Return Value

A new String equivalent to this instance after white space characters are removed from the beginning and end.

See: http://msdn.microsoft.com/en-us/library/aa904317(v=vs.71).aspx

查看更多
We Are One
3楼-- · 2020-04-21 07:10
仙女界的扛把子
4楼-- · 2020-04-21 07:13

Assuming the quotes are really in there, then you want to use a regular expression:

(["'])\s*(.*[^\s])\s*(["'])

Simply replace it with:

$1$2$3

So:

string value = Regex.Replace("\"   value to trim   \"", @"([""'])\s*(.*[^\s])\s*([""'])", "$1$2$3");
查看更多
在下西门庆
5楼-- · 2020-04-21 07:20

What about String.Trim()?

http://msdn.microsoft.com/en-us/library/system.string.trim.aspx

Returns a new string in which all leading and trailing occurrences of a set of specified characters from the current String object are removed.

查看更多
登录 后发表回答