C# Trim string regardless of characters

后端 未结 4 592
无人及你
无人及你 2021-01-24 21:47

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 rep

相关标签:
4条回答
  • 2021-01-24 22:09

    Use String.Trim()

    0 讨论(0)
  • 2021-01-24 22:15

    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");
    
    0 讨论(0)
  • 2021-01-24 22:23

    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.

    0 讨论(0)
  • 2021-01-24 22:36

    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

    0 讨论(0)
提交回复
热议问题