java string contains indexof,为什么contains()方法在Java中的非空字符串中找到空字符串...

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.

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));

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.

Returns true if and only if this string contains the specified sequence of char values.

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值