Removing White spaces from string is not working in c# [duplicate]

眉间皱痕 提交于 2019-12-12 03:48:00

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!