问题
I am trying to remove whitespaces from string but it is not working
string status = " 18820 Pacific Coast Highway
Malibu, CA 90265";
string status1 = status.Trim();
Console.Write(status1);
The above code is not working
Expected Output:
18820 Pacific Coast Highway Malibu, CA 90265
回答1:
Trim()
only works at the start and end of a string. This should work:
string status1 = Regex.Replace(status,@"\s+"," ").Trim();
回答2:
Trim removes leading and trailing symbols (spaces by default). Use Regular expression instead.
RegEx.Replace(status, "\s+", " ").Trim();
回答3:
string status = " 18820 Pacific Coast Highway
Malibu, CA 90265";
string status1 = status.Trim();
Console.Write(status1);
status = status .Replace(" ", "");
But the above code will remove all the whitespaces.
If you want to have whitespace at the end of everyword, then use foreach as mentioned in this link
How to trim whitespace between characters
来源:https://stackoverflow.com/questions/37381525/removing-white-spaces-from-string-is-not-working-in-c-sharp