【问题标题】:initialised string seems to contain string.Empty [duplicate]初始化的字符串似乎包含 string.Empty [重复]
【发布时间】:2011-08-18 11:26:20
【问题描述】:

我不小心跳进去了,不知道为什么会这样

string sample = "Hello World";
if (sample.Contains(string.Empty))
{
    Console.WriteLine("This contains an empty part ? at position " + sample.IndexOf(string.Empty));
    Console.WriteLine(sample.LastIndexOf(string.Empty));
    Console.WriteLine(sample.Length);
}

输出

This contains an empty part ? at position 0

10

11

我对最后一部分很满意,但我不知道为什么这被评估为真的。甚至 IndexofLastIndexOf 也有不同的值。

谁能帮我看看为什么会这样?

编辑

我相信这与我的问题有点相关,并且对那些偶然发现这个问题的人也有帮助。

查看此 SO 链接:Why does "abcd".StartsWith("") return true?

【问题讨论】:

    标签: c# contains string-comparison string


    【解决方案1】:

    来自IndexOf的msdn

    如果值为String.Empty,则返回值为0。

    对于LastIndexOf

    如果 value 是 String.Empty,则返回值是该实例中的最后一个索引位置。

    对于Contains

    如果 value 参数出现在此字符串中,或​​者 value 是空字符串 (""),则为 true;

    【讨论】:

    • @SwDevMan81:不应该是 11 而不是 10 吗?
    • @V4Vendetta - 最后一个索引是 10(0 到 10 是 11 个字符)
    • @SwDevMan81:对不起,我的错误没有读到index,这是否意味着对于上面给出的任何字符串 string.Empty 将始终解析为 true (很高兴知道是否有特例)
    • @V4Vendetta - 是的,如果输入为 String.Empty,它将始终返回 true
    • @SwDevMan81: 好吧,我在why 上看的更多,是这样吗
    【解决方案2】:

    问题:字符串"Hello World"是否包含String.Empty?

    回答:是的。

    每个可能的字符串都包含 String.Empty,因此您的测试正确返回 true。

    如果你想测试你的字符串是否为空,那么下面的代码就是你想要的

    if (string.IsNullOrEmpty(sample)) 
    {
    
    }
    

    【讨论】:

      【解决方案3】:

      这记录在String.Contains Method:

      返回值
      类型:System.Boolean
      true 如果 value 参数出现在此字符串中,或​​者 value 是空字符串 ("");否则,false

      String.IndexOf Method

      如果值为String.Empty,则返回值为0。

      LastIndexOf Method

      如果 value 是 String.Empty,则返回值是该实例中的最后一个索引位置。

      【讨论】:

        猜你喜欢
        • 2018-12-24
        • 2015-07-25
        • 1970-01-01
        • 1970-01-01
        • 2014-06-18
        • 2010-12-03
        • 2013-07-05
        • 2023-01-17
        • 2019-10-03
        相关资源
        最近更新 更多