String.indexOf gives a value one less than expected

前端 未结 1 1999
醉话见心
醉话见心 2021-01-29 16:20

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 numbe         


        
相关标签:
1条回答
  • 2021-01-29 16:56

    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.

    0 讨论(0)
提交回复
热议问题