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条回答
爷、活的狠高调
2楼-- · 2019-01-04 01:08

Not an answer to your question, but to denote a default char you can use just

default(char)

which is same as char.MinValue which in turn is same as \0. One shouldn't use if for something like an empty string though.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-04 01:08

You can also rebuild your string character by character, excluding the characters that you want to get rid of.

Here's an extension method to do this:

    static public string RemoveAny(this string s, string charsToRemove)
    {
        var result = "";
        foreach (var c in s)
            if (charsToRemove.Contains(c))
                continue;
            else
                result += c;

        return result;
    }

It's not slick or fancy, but it works well.

Use like this:

string newString = "My_String".RemoveAny("_"); //yields "MyString"
查看更多
叛逆
4楼-- · 2019-01-04 01:08

I know this one is pretty old, but I encountered an issue recently with having to do multiple replacements to make a file name safe. First, in the latest .NET string.Replace function null is the equivalent to empty character. Having said that, what is missing from .Net is a simple replace all that will replace any character in an array with the desired character. Please feel free to reference the code below (runs in LinqPad for testing).

// LinqPad .ReplaceAll and SafeFileName
void Main()
{

    ("a:B:C").Replace(":", "_").Dump();                     // can only replace 1 character for one character => a_B_C
    ("a:B:C").Replace(":", null).Dump();                    // null replaces with empty => aBC
    ("a:B*C").Replace(":", null).Replace("*",null).Dump();  // Have to chain for multiples 

    // Need a ReplaceAll, so I don't have to chain calls


    ("abc/123.txt").SafeFileName().Dump();
    ("abc/1/2/3.txt").SafeFileName().Dump();
    ("a:bc/1/2/3.txt").SafeFileName().Dump();
    ("a:bc/1/2/3.txt").SafeFileName('_').Dump();
    //("abc/123").SafeFileName(':').Dump(); // Throws exception as expected

}


static class StringExtensions
{

    public static string SafeFileName(this string value, char? replacement = null)
    {
        return value.ReplaceAll(replacement, ':','*','?','"','<','>', '|', '/', '\\');
    }

    public static string ReplaceAll(this string value, char? replacement, params char[] charsToGo){

        if(replacement.HasValue == false){
                return string.Join("", value.AsEnumerable().Where(x => charsToGo.Contains(x) == false));
        }
        else{

            if(charsToGo.Contains(replacement.Value)){
                throw new ArgumentException(string.Format("Replacement '{0}' is invalid.  ", replacement), "replacement");
            }

            return string.Join("", value.AsEnumerable().Select(x => charsToGo.Contains(x) == true ? replacement : x));
        }

    }

}
查看更多
神经病院院长
5楼-- · 2019-01-04 01:09

How about BOM, the magical character Microsoft adds to start of files (at least XML)?

查看更多
欢心
6楼-- · 2019-01-04 01:10

if you want to elliminate the empty char in string the following will work, just convert to any datatype representation you want. thanks,

private void button1_Click(object sender, EventArgs e)
    {

        Int32 i;

        String name;

        Int32[] array_number = new int[100];

        name = "1 3  5  17   8    9    6";

        name = name.Replace(' ', 'x');

        char[] chr = name.ToCharArray();


        for (i = 0; i < name.Length; i++)
        {
            if ((chr[i] != 'x'))
            {
                array_number[i] = Convert.ToInt32(chr[i].ToString());
                MessageBox.Show(array_number[i].ToString());
            }

        }

    }
查看更多
Rolldiameter
7楼-- · 2019-01-04 01:12

Doesn't answer your first question - but for the specific problem you had, you can just use strings instead of chars, right?:

myString.Replace("c", "")

There a reason you wouldn't want to do that?

查看更多
登录 后发表回答