为什么Strings在Java中以“”开头?

时间:2010-10-06 13:27:50

标签: java string logic startswith

  

可能重复:
  Why does “abcd”.StartsWith(“”) return true?

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

考虑以下因素:

public static void main(String args[])
{

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

}

打印出It does

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

有人可以解释一下吗?

8 个答案:

答案 0 :(得分:40)

“”是一个不包含字符的空字符串。没有“空字符”,除非你的意思是空格或空字符,它们都不是空字符串。

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

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

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

1 = 001.000000...
"foo" = "foo" + "" + "" + "" + ...

答案 1 :(得分:11)

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

另请注意,空字符将是" "字符串,而不是空字符串""

答案 2 :(得分:7)

“Hello”以“”开头,它也以“H”开头,它也以“He”开头,它也与“Hel”形成对话......你明白了吗?

答案 3 :(得分:5)

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

答案 4 :(得分: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;
    } 

答案 5 :(得分:3)

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

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

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

答案 6 :(得分:2)

空白是(“”),与空字符串(“”)不同。空格是一个字符,空字符串是没有任何字符。

答案 7 :(得分:0)

空字符串不是空白字符。假设你的问题是空字符串,我猜他们决定离开它,但它似乎很奇怪。他们可以检查长度,但他们没有。