String.indexOf给出的值比预期值小1
我不明白String.index方法的行为。
String peter = "Peter Piper picked a peck of pickled pepper"; System.out.println("The number of p in the sentence is, " + peter.indexOf('p'));
为什么p 8的输出而不是9? 句子中有9个P。
索引从零开始:
↓ Peter Piper picked a peck of pickled pepper 111111111122222222223333333333444 0123456789012345678901234567890123456789012 ↑
第一个 p
在索引8
。
从indexOf()
的javadoc:
返回此对象表示的字符序列中第一次出现的字符的索引 ,如果未出现该字符,则返回
-1
。