简体   繁体   中英

String.indexOf gives a value one less than expected

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM