Метод String lastIndexOf () повертає індекс останнього входження зазначеного символу / підрядка всередині рядка.
Синтаксис lastIndexOf()
методу String теж
string.lastIndexOf(int ch, int index)
або
string.lastIndexOf(string str, int index)
Параметри lastIndexOf ()
Щоб знайти останній індекс символу, lastIndexOf()
приймаються два параметри:
- ch - символ, останній індекс якого потрібно знайти
- індекс (необов’язково) - якщо
index
передано,ch
символ шукається від початку до цього індексу
Щоб знайти останній індекс зазначеного підрядка всередині рядка, lastIndexOf()
приймаються ці два параметри:
- str - рядок, останній індекс якого потрібно знайти
- індекс (необов’язково) - якщо
index
передано,str
рядок шукається від початку до цього індексу
lastIndexOf () Повернене значення
- повертає індекс останнього входження зазначеного символу / рядка
- повертає -1, якщо вказаний символ / рядок не знайдено.
Приклад 1: Рядок Java lastIndexOf ()
// Java String lastIndexOf() with only one parameter class Main ( public static void main(String() args) ( String str1 = "Learn Java"; int result; // getting index of character 'J' result = str1.lastIndexOf('J'); System.out.println(result); // 6 // the last occurrence of 'a' is returned result = str1.lastIndexOf('a'); System.out.println(result); // 9 // character not in the string result = str1.lastIndexOf('j'); System.out.println(result); // -1 // getting the last occurrence of "ava" result = str1.lastIndexOf("ava"); System.out.println(result); // 7 // substring not in the string result = str1.lastIndexOf("java"); System.out.println(result); // -1 ) )
Примітка: Символ 'a'
трапляється кілька разів у "Learn Java"
рядку. У lastIndexOf()
метод повертає індекс останнього входження 'a'
(який 9).
Приклад 2: lastIndexOf () За допомогою параметра fromIndex
class Main ( public static void main(String() args) ( String str1 = "Learn Java programming"; int result; // search from index 0 to 4 // searches the substring "Learn" result = str1.lastIndexOf('r', 4); System.out.println(result); // 3 // search from index 0 to 12 // searcheses the substring "Learn Java pr" result = str1.lastIndexOf('r', 12); System.out.println(result); // 12 // string length is less than 100 // searches the whole string result = str1.lastIndexOf('r', 70); System.out.println(result); // 15 // searches the substring "Learn" result = str1.lastIndexOf("Java", 4); System.out.println(result); // -1 ) )
Примітки:
- Останнє входження
'r'
в"Learn Java programming"
рядок відбувається з індексом 15. Однак здійснюєstr1.lastIndexOf('r', 4)
пошук підрядка"Learn"
. Останній індекс'r'
in"Learn"
знаходиться за індексом 3. str1.lastIndexOf('r', 12)
здійснює пошук у підрядку"Learn Java pr"
. Останній індекс'r'
in"Learn Java pr"
знаходиться за індексом 12.str1.lastIndexOf("Java", 4)
здійснює пошук у підрядку"Learn"
. Оскільки"Java"
в"Learn"
підрядку немає, результат дорівнює -1.
Рекомендуємо прочитати: Java String indexOf ()