0

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
    What do you mean by 'not working'? What is the output? – Andrew Li May 23 '16 at 01:46
  • 1
    It seems to be working. `.Trim()` does not remove ALL whitespaces. it removes "extra" whitespaces. see examples here: http://stackoverflow.com/questions/3381952/how-automatically-remove-all-white-spaces-start-or-end-in-a-string?answertab=active#tab-top .. Also, If you want to remove ALL of them, use the `.Replace()` method like this: `status.Replace(" ", "");` – ᴛʜᴇᴘᴀᴛᴇʟ May 23 '16 at 01:48
  • try to use replace – Govind May 23 '16 at 01:51

3 Answers3

4

Trim removes leading and trailing symbols (spaces by default). Use Regular expression instead.

RegEx.Replace(status, "\s+", " ").Trim();
Alex Kudryashev
  • 9,120
  • 3
  • 27
  • 36
2

Trim() only works at the start and end of a string. This should work:

string status1 = Regex.Replace(status,@"\s+"," ").Trim();
Alastair Brown
  • 1,598
  • 8
  • 12
-1
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

Community
  • 1
  • 1
Govind
  • 979
  • 4
  • 14
  • 45