Home  >  Article  >  Java  >  Java lastIndexOf principle analysis

Java lastIndexOf principle analysis

Guanhui
Guanhuiforward
2020-07-22 17:41:023342browse

Java lastIndexOf principle analysis

lastIndexOf returns its position in the string according to the search conditions. Spaces are also counted. If there is no such character in the string, -1 is returned.

There are four main methods:

  • lastIndexOf(int ch), which returns the last occurrence of the specified character in this string. index.

  • lastIndexOf(int ch , int fromIndex) , returns the index of the last occurrence of the specified character in this string, and starts a reverse search from the specified index.

  • lastIndexOf(String str), returns the index of the rightmost occurrence of the specified substring in this string.

  • lastIndexOf(String str , int fromIndex), returns the index of the last occurrence of the specified substring in this string, and starts the reverse search from the specified index.

Parameters

  • ch -- Characters.

  • fromIndex -- The index position to start the search.

  • #str -- The substring to search for.

Return value

The index value of the first occurrence of the specified substring in the string.

Example:

String str = "01234567890123456789";
//查找字符串“01234567890123456789”中字符‘8'所在的位置(索引从0开始,从前往后搜索)
System.out.println(str.lastIndexOf('8')); //18
//查找字符串“01234567890123456789”中字符‘8'所在的位置,从索引为9的位置,即“0123456789”,从后往前搜索。
System.out.println(str.lastIndexOf('8',9)); //8
//查找字符串“01234567890123456789”中字符串‘56'所在的位置(索引从0开始,从前往后搜索),返回的是“56”中“5”的位置。
System.out.println(str.lastIndexOf("56")); //15
//查找字符串“01234567890123456789”中字符‘8'所在的位置,从索引为9的位置,即“0123456789”,从后往前搜索,返回的是“56”中“5”的位置。
System.out.println(str.lastIndexOf("56",9)); //5

Note: System.out.println(str.lastIndexOf("56",5)) In this example, it stands to reason that in "012345 "56" cannot be found, but the returned value is not -1, but 5.

After testing, when searching for a string, only the subscript of the first character in the matched string is returned. So even if you set the value of fromIndex to "5", you can match "567890123456789", and the return value is also 5.

Similar example:

String str1 = "Hello World!";
System.out.println(str1.lastIndexOf('o')); //7
System.out.println(str1.lastIndexOf("o ",4)); //4
System.out.println(str1.lastIndexOf("o World",4)); //4

Recommended tutorial: "Java Tutorial"

The above is the detailed content of Java lastIndexOf principle analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete