20

可能重复:
为什么“abcd”.StartsWith(“”) 返回 true?

在通过一些代码进行调试时,我发现我的验证的一个特定部分是使用.startsWith()String 类上的方法来检查 String 是否以空白字符开头

考虑到以下几点:

public static void main(String args[])
{

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

}

它打印出来It does

我的问题是,为什么字符串以空白字符开头?我假设在引擎盖下字符串本质上是字符数组,但在这种情况下,我会认为第一个字符是H

谁能解释一下?

4

8 回答 8

40

"" 是一个不包含任何字符的空字符串。没有“空字符”,除非您指的是空格或空字符,它们都不是空字符串。

您可以将字符串视为以无限数量的空字符串开头,就像您可以将数字视为以无限数量的前导零开头而不改变其含义一样。

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

字符串也以无限数量的空字符串结尾(就像带零的十进制数一样):

1 = 001.000000...
"foo" = "foo" + "" + "" + "" + ...
于 2010-10-06T13:29:52.980 回答
11

似乎您的代码中存在误解。您的语句s.startsWith("")检查字符串是否以空字符串(而不是空白字符)开头。无论如何,这可能是一个奇怪的实现选择:所有字符串都会说您以空字符串开头。

还要注意一个空白字符将是" "字符串,而不是你的空字符串""

于 2010-10-06T13:31:02.613 回答
7

“你好”以“”开头,它也以“H”开头,它也以“He”开头,它也以“Hel”开头……你明白吗?

于 2010-10-06T14:05:55.743 回答
5

那 "" 不是一个空白,它是一个空字符串。我猜API在问这个问题是它的一个子字符串。零长度的空字符串是所有内容的子字符串。

于 2010-10-06T13:30:35.827 回答
4

空字符串 ( "") 基本上“满足”每个字符串。在您的示例中,java 调用

s.startsWith(""); 

s.startsWith("", 0);

它基本上遵循“一个空元素(字符串)满足其约束(你的字符串句子)”的原则。

来自 String.java

/**
     * Tests if the substring of this string beginning at the
     * specified index starts with the specified prefix.
     *
     * @param   prefix    the prefix.
     * @param   toffset   where to begin looking in this string.
     * @return  <code>true</code> if the character sequence represented by the
     *          argument is a prefix of the substring of this object starting
     *          at index <code>toffset</code>; <code>false</code> otherwise.
     *          The result is <code>false</code> if <code>toffset</code> is
     *          negative or greater than the length of this
     *          <code>String</code> object; otherwise the result is the same
     *          as the result of the expression
     *          <pre>
     *          this.substring(toffset).startsWith(prefix)
     *          </pre>
     */
    public boolean startsWith(String prefix, int toffset) {
    char ta[] = value;
    int to = offset + toffset;
    char pa[] = prefix.value;
    int po = prefix.offset;
    int pc = prefix.count;
    // Note: toffset might be near -1>>>1.
    if ((toffset < 0) || (toffset > count - pc)) {
        return false;
    }
    while (--pc >= 0) {
        if (ta[to++] != pa[po++]) {
            return false;
        }
    }
    return true;
    } 
于 2010-10-06T13:45:50.050 回答
4

对于采用自动机理论的人来说,这是有道理的,因为空字符串 ε 是任何字符串的子字符串,也是连接标识元素,即:

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

所以是的,每个字符串“startWith”都是空字符串。另请注意(正如许多其他人所说),空字符串与空白或空字符不同。

于 2010-10-06T21:29:02.847 回答
2

空格是 (" "),这与空字符串 ("") 不同。空格是一个字符,空字符串是没有任何字符。

于 2010-10-06T13:31:32.397 回答
0

空字符串不是空白字符。假设您的问题是空字符串,我猜他们决定保留这种方式,但看起来确实很奇怪。他们本可以检查长度,但没有。

于 2010-10-06T21:37:52.020 回答