Why does “abcd”.StartsWith(“”) return true?

2019-01-01 15:55发布

Title is the entire question. Can someone give me a reason why this happens?

12条回答
只若初见
2楼-- · 2019-01-01 16:09

If you think of it in regular expressions terms, it makes sense. Every string (not just "abcd", also "" and "sdf\nff") , returns true when evaluating the regular expression of 'starts with empty string'.

查看更多
时光乱了年华
3楼-- · 2019-01-01 16:12

In C#, the reason it returns true is that the developers specifically coded for it.

If you check out the source code, you'll find specific logic to handle an empty string:

public Boolean StartsWith(String value)
{
    return StartsWith(value, StringComparison.CurrentCulture);
}

public Boolean StartsWith(String value, StringComparison comparisonType)
{
    ...

    if (value.Length == 0)
    {
        return true;
    }
查看更多
千与千寻千般痛.
4楼-- · 2019-01-01 16:16

Why does “abcd”.StartsWith(“”) return true?

THE REAL ANSWER:

It has to be that way otherwise you'd have the case where

    "".startsWith("") == false 
    "".equals("") == true

    but yet

    "a".startsWith("a") == true
    "a".equals("a") == true

and then we'd have Y2K all over again because all the bank software that depends on equal strings starting with themselves will get our accounts mixed up and suddenly Bill Gates will have my wealth and I'd have his, and damn it! Fate just isn't that kind to me.

查看更多
浮光初槿花落
5楼-- · 2019-01-01 16:16

Just for the record, String.StartsWith() internally calls the method System.Globalization.CultureInfo.IsPrefix() which makes the following check explicitly:

if (prefix.Length == 0)
{
    return true;
}
查看更多
唯独是你
6楼-- · 2019-01-01 16:18

The first N characters of the two strings are identical. N being the length of the second string, i.e. zero.

查看更多
牵手、夕阳
7楼-- · 2019-01-01 16:21

Let's just say "abcd".StartsWith("") returns false.

if so then what does the following expression eval to, true or false:

 ("abcd".Substring(0,0) == "")

it turns out that evals to true, so the string does start with the empty string ;-), or put in other words, the substring of "abcd" starting at position 0 and having 0 length equals the empty string "". Pretty logical imo.

查看更多
登录 后发表回答