2011-05-04 33 views
9

我跳进这个意外并没有任何线索,为什么发生这种情况初始化字符串似乎包含的String.Empty

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?

回答

16

从MSDN什么IndexOf

如果值的String.Empty,返回值是0。

对于LastIndexOf

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

Contains对于

真如果发生此字符串中的值参数,或者如果值是空字符串(“”);

+0

@ SwDevMan81:应该不是11而不是10? – V4Vendetta 2011-05-04 11:50:12

+0

@ V4Vendetta - 最后的索引是10(0到10是11个字符) – SwDevMan81 2011-05-04 11:51:17

+0

@ SwDevMan81:对不起,我的错误没有读取'index',所以它暗示了对于上面给出的任何字符串string.Empty将始终解析为true (很高兴知道是否有例外情况) – V4Vendetta 2011-05-04 11:56:03

4

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

答案:是的。

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

如果你想测试,如果你的字符串为空,然后将下面的代码是你想要

if (string.IsNullOrEmpty(sample)) 
{ 

} 
1

这是记录在String.Contains Method

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

而且在String.IndexOf Method

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

而且在LastIndexOf Method

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