String.indexOf给出的值比预期值小1 [英] String.indexOf gives a value one less than expected

查看:152
本文介绍了String.indexOf给出的值比预期值小1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白方法的String.index的行为。

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

为什么p 8的输出而不是9?句子中有9个P。

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

推荐答案

索引从零开始:

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

第一个 p 在索引 8

来自 indexOf()


返回角色中第一次出现索引此对象表示的序列,或 -1 如果字符未出现。

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.

这篇关于String.indexOf给出的值比预期值小1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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