Java String.indexOf和空字符串 [英] Java String.indexOf and empty Strings

查看:586
本文介绍了Java String.indexOf和空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为什么 String.indexOf 在请求字符串中空字符串的索引时返回0(而不是-1)。

I'm curious why the String.indexOf is returning a 0 (instead of -1) when asking for the index of an empty string within a string.

Javadocs只说这个方法返回指定字符串的字符串中的索引,如果找不到字符串,则返回-1。

The Javadocs only say this method returns the index in this string of the specified string, -1 if the string isn't found.

对我来说,这种行为似乎非常意外,我原以为-1。任何想法为什么会发生这种意外行为?我至少认为这在方法的Javadocs中值得注意...

To me this behavior seems highly unexpected, I would have expected a -1. Any ideas why this unexpected behavior is going on? I would at the least think this is worth a note in the method's Javadocs...

System.out.println("FOO".indexOf("")); // outputs 0 wtf!!!
System.out.println("FOO".indexOf("bar")); // outputs -1 as expected
System.out.println("FOO".indexOf("F")); // outputs 0 as expected
System.out.println("".indexOf("")); // outputs 0 as expected, I think


推荐答案

空字符串无处不在,无处可去。它始终在所有的弦中,渗透着它们存在的本质,但是当你寻求它时,你永远不会瞥见它。

The empty string is everywhere, and nowhere. It is within all strings at all times, permeating the essence of their being, yet as you seek it you shall never catch a glimpse.

你能算多少空字符串在一个字符串的开头? Mu

How many empty strings can you fit at the beginning of a string? Mu

学生对老师说,


<老师,我相信我已经找到了空字符串的本质。空的绳子就像一团灰尘,当灰尘在房间里自由漂浮,在阳光下闪闪发光时,它会自由浮动穿过绳子。

Teacher, I believe that I have found the nature of the empty string. The empty string is like a particle of dust, and it floats freely through a string as dust floats freely through the room, glistening in a beam of sunlight.

老师回应了学生,


嗯。一个好的概念。现在告诉我,灰尘在哪里,阳光在哪里?

Hmm. A fine notion. Now tell me, where is the dust, and where is the sunlight?

老师用带子敲打学生并指示他继续他的冥想。

The teacher struck the student with a strap and instructed him to continue his meditation.

这篇关于Java String.indexOf和空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆