String.indexOf gives a value one less than expected

柔情痞子 提交于 2019-12-02 23:53:03

问题


I do not understand the behaviour of the String.index Of method.

String peter = "Peter Piper picked a peck of pickled pepper";
  System.out.println("The number of p in the sentence is, " + peter.indexOf('p')); 

Why is the output of p 8 and not 9? There are 9 P's in the sentence.


回答1:


Indexes are zero-based:

        ↓
Peter Piper picked a peck of pickled pepper
          111111111122222222223333333333444
0123456789012345678901234567890123456789012
        ↑

The first p is at index 8.

From the javadoc of indexOf():

Returns the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.



来源:https://stackoverflow.com/questions/34214064/string-indexof-gives-a-value-one-less-than-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!