Why is there no Char.Empty like String.Empty?

2019-01-04 00:37发布

Is there a reason for this? I am asking because if you needed to use lots of empty chars then you get into the same situation as you would when you use lots of empty strings.

Edit: The reason for this usage was this:

myString.Replace ('c', '')

So remove all instances of 'c's from myString.

19条回答
Deceive 欺骗
2楼-- · 2019-01-04 01:27

If you want to remove characters that satisfy a specific condition, you may use this:

string s = "SoMEthInG";
s = new string(s.ToCharArray().Where(c => char.IsUpper(c)).ToArray());

(This will leave only the uppercase characters in the string.)

In other words, you may convert the string to an IEnumerable<char>, make changes on it and then convert it back to a string as shown above.

Again, this enables to not only remove a specific char because of the lambda expression, although you can do so if you change the lambda expression like this: c => c != 't'.

查看更多
登录 后发表回答