Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all whitespace characters from a String?

Dear fellow programmers,

I am coding something in C# Visual Studio 2013 and I have just realized I might not need to use Trim() when I do Replace(" ", string.Empty).

An example follows:

SanitizedString = RawString
    .Replace("/", string.Empty)
    .Replace("\\", string.Empty)
    .Replace(" ", string.Empty)
    .Trim();

As I previously had this code structured differently, I haven't noticed it:

SanitizedString = RawString.Trim()
    .Replace("/", string.Empty)
    .Replace("\\", string.Empty)
    .Replace(" ", string.Empty);

I am aware these methods work different, as Trim() removes all whitespace characters, whereas Replace(" ", string.Empty) removes only space characters.

That's why I have a different question.

I don't see any obvious way to achieve that with Replace. My question is how would I go about it when I wish to remove all whitespace characters from the string?

I found the following:

Efficient way to remove ALL whitespace from String?

But as I have never used regular expressions, I hesitate on how to apply it to string?

like image 578
LinuxSecurityFreak Avatar asked Sep 22 '17 11:09

LinuxSecurityFreak


1 Answers

Try using Linq in order to filter out white spaces:

  using System.Linq;

  ... 

  string source = "abc    \t def\r\n789";
  string result = string.Concat(source.Where(c => !char.IsWhiteSpace(c)));

  Console.WriteLine(result);

Outcome:

abcdef789
like image 173
Dmitry Bychenko Avatar answered Oct 14 '22 09:10

Dmitry Bychenko