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条回答
ゆ 、 Hurt°
2楼-- · 2019-01-04 01:02

You could use nullable chars.

char? c
查看更多
forever°为你锁心
3楼-- · 2019-01-04 01:02

If you don't need the entire string, you can take advantage of the delayed execution:

public static class StringExtensions
{
    public static IEnumerable<char> RemoveChar(this IEnumerable<char> originalString, char removingChar)
    {
        return originalString.Where(@char => @char != removingChar);
    }
}

You can even combine multiple characters...

string veryLongText = "abcdefghijk...";

IEnumerable<char> firstFiveCharsWithoutCsAndDs = veryLongText
            .RemoveChar('c')
            .RemoveChar('d')
            .Take(5);

... and only the first 7 characters will be evaluated :)

EDIT: or, even better:

public static class StringExtensions
{
    public static IEnumerable<char> RemoveChars(this IEnumerable<char> originalString,
        params char[] removingChars)
    {
        return originalString.Except(removingChars);
    }
}

and its usage:

        var veryLongText = "abcdefghijk...";
        IEnumerable<char> firstFiveCharsWithoutCsAndDs = veryLongText
            .RemoveChars('c', 'd')
            .Take(5)
            .ToArray(); //to prevent multiple execution of "RemoveChars"
查看更多
老娘就宠你
4楼-- · 2019-01-04 01:02

In terms of C# language, the following may not make much sense. And this is not a direct answer to the question. But fowlloing is what I did in one of my business scenario

        char? myCharFromUI = Convert.ToChar(" ");
        string myStringForDatabaseInsert = myCharFromUI.ToString().Trim();
        if (String.IsNullOrEmpty(myStringForDatabaseInsert.Trim()))
        {
            Console.Write("Success");
        }

The null and white space had different business flows in my project. While inserting into database, I need to insert empty string to the database if it is white space.

查看更多
霸刀☆藐视天下
5楼-- · 2019-01-04 01:05

the same reason there isn't an int.Empty. Containers can be empty. Scalar values cannot be. If you mean 0 (which is not empty), then use '\0'. If you mean null, then use null :)

查看更多
We Are One
6楼-- · 2019-01-04 01:06

There's no such thing as an empty character. It always contains something. Even '\0' is a character.

查看更多
乱世女痞
7楼-- · 2019-01-04 01:06
myString = myString.Replace('c'.ToString(), "");

OK, this is not particularly elegant for removing letters, since the .Replace method has an overload that takes string parameters. But this works for removing carriage returns, line feeds, tabs, etc. This example removes tab characters:

myString = myString.Replace('\t'.ToString(), "");
查看更多
登录 后发表回答