为什么Strings在Java中以“”开头?
可能重复:
为什么“abcd”.StartsWith(“”)返回true?
在通过一些代码调试的过程中,我发现我validation的一个特定部分是在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
谁能解释一下吗?
“”是一个不包含字符的空字符串。 没有“空字符”,除非您指的是空格或空字符,它们都不是空字符串。
您可以将字符串视为以无限数量的空字符串开头,就像您可以将数字视为以无限数量的前导零开头而不改变其含义。
1 = ...00001 "foo" = ... + "" + "" + "" + "foo"
字符串也以无限数量的空字符串结尾(带有零的十进制数字):
1 = 001.000000... "foo" = "foo" + "" + "" + "" + ...
好像你的代码中存在误解。 您的语句s.startsWith("")
检查字符串是否以空字符串开头(而不是空白字符)。 它可能是一个奇怪的实现选择,无论如何,它是这样的:所有字符串都会说你以空字符串开头。
另请注意,空字符将是" "
字符串,而不是空字符串""
。
“Hello”以“”开头,它也以“H”开头,它也以“He”开头,它也与“Hel”形成对话……你看到了吗?
那个“”不是空白,它是一个空字符串。 我想API问的问题是这是一个子串。 零长度空字符串是一切的子字符串。
空字符串( ""
)基本上“满足”每个字符串。 在你的例子中,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
true
if the character sequence represented by the * argument is a prefix of the substring of this object starting * at indextoffset
;false
otherwise. * The result isfalse
iftoffset
is * negative or greater than the length of this *String
object; otherwise the result is the same * as the result of the expression *
* this.substring(toffset).startsWith(prefix) *
*/ 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; }
对于采用自动机理论的人来说,这是有道理的,因为空字符串ε是任何字符串的子字符串,也是连接标识元素,即:
for all strings x, ε + x = x, and x + ε = x
所以是的,每个字符串“startWith”为空字符串。 另请注意(正如许多其他人所说),空字符串与空字符或空字符不同。
空白是(“”),它与空字符串(“”)不同。 空格是一个字符,空字符串是没有任何字符。
空字符串不是空白字符。 假设你的问题是空字符串,我猜他们决定离开它,但它确实看起来很奇怪。 他们可以检查长度,但他们没有。