本文介绍了为什么contains()方法在Java中的非空字符串中找到空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在Java的 String.indexOf() String.contains()方法中发现的奇怪行为。如果我有非空字符串说 blablabla 并且我尝试在其中查找空字符串,它总是返回 true 而我希望它返回 false

This is a weird behavior I found with Java's String.indexOf() and String.contains() methods. If I have a non-empty string says blablabla and I try to look for an empty string inside it, it always returns true whereas I would expect it to return false.

所以基本上,为什么下面的代码是否返回true和0?

So basically, why does the code below return true and 0 ?

String testThis = "";
String fileName = "blablablabla";
System.out.println(fileName.contains(testThis));
System.out.println(fileName.indexOf(testThis));

逻辑上(至少对我来说)不会出现在 blablablabla 但是 indexOf()这样说,为什么?

Logically (at least to me) "" does not occur in blablablabla but indexOf("") says it does, why?

推荐答案

每个字符串都会出现一个空字符串。具体而言,字符串的连续子集必须与空字符串匹配。任何空子集都是连续的,任何字符串都有一个空字符串作为这样的子集。

An empty string occurs in every string. Specifically, a contiguous subset of the string must match the empty string. Any empty subset is contiguous and any string has an empty string as such a subset.

任何字符串,开头,结尾和字符之间都存在一组空的char值。出于任何事情,你什么都不提取。从一个物理的字符串/纱线我可以说它内部存在零长度部分。

An empty set of char values exists in any string, at the beginning, end, and between characters. Out of anything, you can extract nothing. From a physical piece of string/yarn I can say that a zero-length portion exists within it.

如果包含返回true,则可能存在 substring(调用以获取要查找的字符串。aaa.substring(1,1)应返回 ,但请不要引用我,因为我目前还没有IDE。

If contains returns true there is a possible substring( invocation to get the string to find. "aaa".substring(1,1) should return "", but don't quote me on that as I don't have an IDE at the moment.

这篇关于为什么contains()方法在Java中的非空字符串中找到空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 04:34