为什么没有像String.Empty那样的Char.Empty?

发布于 2024-09-18 06:40:17 字数 193 浏览 7 评论 0原文

这是有原因的吗?我这样问是因为如果您需要使用大量空字符,那么您会遇到与使用大量空字符串时相同的情况。

编辑:这种用法的原因是这样的:

myString.Replace ('c', '')

因此从 myString 中删除 'c' 的所有实例。

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' from myString.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

极度宠爱 2024-09-25 06:40:58

从字符串中全面删除字符的最简单方法是修剪它

cl = cl.Trim(' ');

删除字符串中的所有空格

Easiest way to blanket remove a character from string is to Trim it

cl = cl.Trim(' ');

Removes all of the spaces in a string

最美的太阳 2024-09-25 06:40:57

使用

myString.Replace ("c", "")

use

myString.Replace ("c", "")
城歌 2024-09-25 06:40:55
public static string QuitEscChars(this string s) 
{
    return s.Replace(((char)27).ToString(), "");
}
public static string QuitEscChars(this string s) 
{
    return s.Replace(((char)27).ToString(), "");
}
手心的温暖 2024-09-25 06:40:54

BOM 怎么样,微软添加到文件开头(至少是 XML)的神奇字符?

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

你是年少的欢喜 2024-09-25 06:40:52

我们是这样做的:
myString.Replace('''.ToString(), "");

here is how we do it :
myString.Replace ('''.ToString(), "");

︶ ̄淡然 2024-09-25 06:40:51

如果你想消除字符串中的空字符,下面的方法就可以了。只需转换为您想要的任何数据类型表示形式即可。

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());
        }
    }
}

If you want to eliminate the empty char in string, the following will work. Just convert to any datatype representation you want.

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());
        }
    }
}
榕城若虚 2024-09-25 06:40:49

就C#语言而言,以下内容可能没有多大意义。这并不是问题的直接答案。但以下是我在一个业务场景中所做的事情。

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

nullwhite space 在我的项目中具有不同的业务流程。在插入数据库时​​,如果它是空格,我需要将空字符串插入到数据库中。

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

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.

顾铮苏瑾 2024-09-25 06:40:48

如果要删除满足特定条件的字符,可以使用以下命令:(

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

这将只保留字符串中的大写字符。)

换句话说,您可以将字符串“使用”为 IEnumerable,对其进行更改,然后将其转换回字符串,如上所示。

同样,这不仅可以因为 lambda 表达式而删除特定的字符,尽管如果您像这样更改 lambda 表达式也可以这样做: c != 't'。

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

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

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

In other words, you may "use" the string as 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'.

迷爱 2024-09-25 06:40:47

我知道这个已经很旧了,但我最近遇到了一个问题,必须进行多次替换才能确保文件名安全。首先,在最新的.NET string.Replace函数中,null相当于空字符。话虽如此,.Net 缺少的是一个简单的替换全部功能,它将用所需的字符替换数组中的任何字符。请随意参考下面的代码(在 LinqPad 中运行进行测试)。

// 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));
        }

    }

}

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));
        }

    }

}
岁吢 2024-09-25 06:40:46

您还可以逐个字符地重建字符串,不包括要删除的字符。

这是执行此操作的扩展方法:

    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;
    }

它并不圆滑或花哨,但效果很好。

像这样使用:

string newString = "My_String".RemoveAny("_"); //yields "MyString"

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"
清君侧 2024-09-25 06:40:44

如果您查看 Replace(String, String) 重载 您可以在备注部分看到,如果第二个参数是 null 那么它将删除您指定的所有实例。因此,如果您仅使用 myString = myString.Replace("c", null); ,它将删除字符串中的每个 c

If you look at the documentation for Replace(String, String) overload for String.Replace you can see in the remarks section that if the second argument is a null then it will remove all instances of what you specified. Therefore if you just use myString = myString.Replace("c", null); it will delete every c in the string.

度的依靠╰つ 2024-09-25 06:40:42

没有回答您的第一个问题 - 但对于您遇到的具体问题,您可以使用字符串而不是字符,对吧?:

myString.Replace("c", "")

您有理由不想这样做吗?

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?

不打扰别人 2024-09-25 06:40:40

char 是值类型,因此它的值不能为 null。 (除非它包装在 Nullable 容器中)。

由于它不能为空,因此 in 包含一些数字代码,并且每个代码都映射到某个字符。

A char is a value type, so its value cannot be null. (Unless it is wrapped in a Nullable container).

Since it can't be null, in contains some numeric code and each code is mapped to some character.

っ左 2024-09-25 06:40:39

与没有 int.Empty 的原因相同。容器可以为空,但标量值不能为空。如果您的意思是 0(不为空),则使用 '\0'。如果您的意思是 null,则使用 null :)

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

朦胧时间 2024-09-25 06:40:38
myString = myString.Replace('c'.ToString(), "");

好的,这对于删除字母来说并不是特别优雅,因为 .Replace 方法有一个采用字符串参数的重载。但这适用于删除回车符、换行符、制表符等。此示例删除制表符:

myString = myString.Replace('\t'.ToString(), "");
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(), "");
笨笨の傻瓜 2024-09-25 06:40:37

如果您不需要整个字符串,您可以利用延迟执行:

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

您甚至可以组合多个字符...

string veryLongText = "abcdefghijk...";

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

...并且只会评估前 7 个字符:)

编辑:或者,甚至更好:

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

和它的用法:

        var veryLongText = "abcdefghijk...";
        IEnumerable<char> firstFiveCharsWithoutCsAndDs = veryLongText
            .RemoveChars('c', 'd')
            .Take(5)
            .ToArray(); //to prevent multiple execution of "RemoveChars"

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"
那小子欠揍 2024-09-25 06:40:35

不是您问题的答案,但要表示默认的 char,您可以使用

default(char)

char.MinValue 相同的值,而 char.MinValue 又与 \0< /代码>。不过,人们不应该将它用于诸如空字符串之类的东西。

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 it for something like an empty string though.

月下客 2024-09-25 06:40:34

您可以使用 可空 字符。

char? c

You could use nullable chars.

char? c
往日 2024-09-25 06:40:32

使用 Char.MinValue 其作用与“\0”相同。但要注意它与String.Empty不同。

Use Char.MinValue which works the same as '\0'. But be careful it is not the same as String.Empty.

风向决定发型 2024-09-25 06:40:31

不存在所谓的空字符。它总是包含某些东西。甚至“\0”也是一个字符。

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

梦醒时光 2024-09-25 06:40:28

与字符串不同,字符是具有固定大小的离散事物。字符串实际上是字符的容器。

因此,Char.Empty 在这种情况下并没有真正的意义。如果你有一个字符,它就不是空的。

A char, unlike a string, is a discrete thing with a fixed size. A string is really a container of chars.

So, Char.Empty doesn't really make sense in that context. If you have a char, it's not empty.

怀中猫帐中妖 2024-09-25 06:40:27

这种用法的原因是:myString.Replace ('c', '')
因此,从 myString 中删除 'c' 的所有实例。

要从字符串中删除特定字符,您可以使用字符串重载:

 myString = myString.Replace ("c", String.Empty);

您的语句

 myString.Replace ('c', '\0')

不会删除任何字符。它只会将它们替换为 '\0' (字符串结尾,EOS),并产生不同的结果。某些字符串操作可能会在遇到 EOS 时停止,但在 .NET 中,大多数操作会将其视为任何其他字符。最好尽可能避免 '\0'

The reason for this usage was this: myString.Replace ('c', '')
So remove all instances of 'c' from myString.

To remove a specific char from a string you can use the string overload:

 myString = myString.Replace ("c", String.Empty);

Your statement

 myString.Replace ('c', '\0')

Won't remove any characters. It will just replace them with '\0' (End-Of-String, EOS), with varying consequences. Some string operations might stop when encountering an EOS but in .NET most actions will treat it like any other char. Best to avoid '\0' as much as possible.

似狗非友 2024-09-25 06:40:25

不存在空字符这样的东西。您能得到的最接近的是 '\0',即 Unicode“null”字符。鉴于您可以将其嵌入到字符串文字中或非常容易地单独表达它,为什么您需要一个单独的字段呢?同样,“很容易混淆 ””” “” 参数不适用于 '\0'

如果你能举一个例子来说明你想在哪里使用它以及为什么你认为它会更好,这可能会有所帮助......

There's no such thing as an empty char. The closest you can get is '\0', the Unicode "null" character. Given that you can embed that within string literals or express it on its own very easily, why would you want a separate field for it? Equally, the "it's easy to confuse "" and " "" arguments don't apply for '\0'.

If you could give an example of where you'd want to use it and why you think it would be better, that might help...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文