初始化的字符串似乎包含 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);
}
输出
这包含一个空部分?在位置 0
10
11
我对最后一部分很满意,但我不知道为什么它被评估为 true。甚至 Indexof
和 LastIndexOf
也有单独的值。
谁能帮我解释为什么会这样吗?
编辑
我相信这与我的问题有点相关,并且对那些偶然发现这个问题的人也有帮助。
I jumped into this accidentally and have no clue as to why this is happening
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);
}
Output
This contains an empty part ? at position 0
10
11
I am happy with the last part, but i have no idea why this is evaluated true. Even Indexof
and LastIndexOf
have separate values.
Could anyone help me out on why is this so?
EDIT
I believe this is a bit relevant to my question and would be also helpful to those who stumble upon this question.
See this SO link: Why does "abcd".StartsWith("") return true?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 IndexOf 的 msdn
对于 LastIndexOf
对于包含
From msdn for IndexOf
For LastIndexOf
For Contains
问题:字符串
“Hello World”
是否包含String.Empty?回答:是的。
每个可能的字符串都包含 String.Empty,因此您的测试正确返回 true。
如果您想测试字符串是否为空,那么以下代码就是您想要的
Question: Does the string
"Hello World"
contain String.Empty?Answer: Yes.
Every possible string contains String.Empty, so your test is correctly returning true.
If you are trying to test if your string is empty, then the following code is what you want
这记录在 String.Contains 方法:
并在 String.IndexOf 方法
并且在 LastIndexOf 方法
This is documented in the String.Contains Method:
And in String.IndexOf Method
And in LastIndexOf Method