Why do Strings start with a “” in Java? [duplicate

2019-02-11 20:28发布

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

Whilst debugging through some code I found a particular piece of my validation was using the .startsWith() method on the String class to check if a String started with a blank character

Considering the following :

public static void main(String args[])
{

    String s = "Hello";
    if (s.startsWith(""))
    {
        System.out.println("It does");
    }

}

It prints out It does

My question is, why do Strings start off with a blank character? I'm presuming that under the hood Strings are essentially character arrays, but in this case I would have thought the first character would be H

Can anyone explain please?

8条回答
看我几分像从前
2楼-- · 2019-02-11 21:03

"Hello" starts with "" and it also starts with "H" and it also starts with "He" and it also sharts with "Hel" ... do you see?

查看更多
萌系小妹纸
3楼-- · 2019-02-11 21:05

Seems like there is a misunderstanding in your code. Your statement s.startsWith("") checks if string starts with an empty string (and not a blank character). It may be a weird implementation choice, anyway, it's as is : all strings will say you they start with an empty string.

Also notice a blank character will be the " " string, as opposed to your empty string "".

查看更多
\"骚年 ilove
4楼-- · 2019-02-11 21:06

A blank is (" "), that's different from an empty string (""). A blank space is a character, the empty string is the absence of any character.

查看更多
我只想做你的唯一
5楼-- · 2019-02-11 21:10

"" is an empty string containing no characters. There is no "empty character", unless you mean a space or the null character, neither of which are empty strings.

You can think of a string as starting with an infinite number of empty strings, just like you can think of a number as starting with an infinite number of leading zeros without any change to the meaning.

1 = ...00001
"foo" = ... + "" + "" + "" + "foo"

Strings also end with an infinite number of empty strings (as do decimal numbers with zeros):

1 = 001.000000...
"foo" = "foo" + "" + "" + "" + ...
查看更多
ゆ 、 Hurt°
6楼-- · 2019-02-11 21:14

For folks who have taken automata theory, this makes sense because the empty string ε is a substring of any string and also is the concatenation identity element, ie:

for all strings x, ε + x = x, and x + ε = x

So yes, every string "startWith" the empty string. Also note (as many others said it), the empty string is different from a blank or null character.

查看更多
走好不送
7楼-- · 2019-02-11 21:15

That "" is not a blank it's an empty string. I guess that the API is asking the question is this a substring of that. And the zero-length empty string is a substring of everything.

查看更多
登录 后发表回答