Зміст курсу
Java Extended
Java Extended
Метод indexof()
Як знайти індекс заданого символу у String?
Для знаходження індексу першого входження певної літери клас String
надає метод indexOf()
. Цей метод перевантажений і має декілька реалізацій. Розглянемо, що робить кожна з них:
indexOf(String str)
indexOf(String str)
— у цьому методі параметр визначає, що саме ми шукаємо. Це може бути одна літера в подвійних лапках (""
), послідовність літер або навіть слово. Метод повертає індекс першого входження вказаного параметра у рядку. Наприклад, знайдемо індекс літери "l"
у рядку "Hello"
:
Main.java
package com.example; // do not modify the code below this comment public class Main { public static void main(String[] args) { String hello = "Hello"; // find the index of the first appearance of the letter "l" int index = hello.indexOf("l"); // output the index of the first occurrence of "l" System.out.println("First appearance of the letter 'l' is on index " + index); } }
У наведеному вище прикладі ми ініціалізували змінну index
за допомогою методу indexOf("l")
. Тепер ця змінна містить індекс першого входження літери "l"
у рядку "Hello"
.
indexOf(String str, int fromIndex)
indexOf(String str, int fromIndex)
— перший параметр такий самий, як і раніше, і визначає, що саме ми шукаємо.
Другий параметр визначає початковий індекс, з якого починається пошук. Наприклад, у слові "Hello"
є 2 входження літери "l"
, і ми хочемо знайти індекс другого входження. З першого прикладу відомо, що перше входження знаходиться на індексі 2
, тому встановимо параметр fromIndex
на 3 і знайдемо індекс другої "l"
:
Main.java
package com.example; // do not modify the code below this comment public class Main { public static void main(String[] args) { String hello = "Hello"; // find the index of the first appearance of the letter "l" int firstIndex = hello.indexOf("l"); // find the index of the second appearance of the letter "l", starting from the position after the first "l" int secondIndex = hello.indexOf("l", firstIndex + 1); // output the index of the second occurrence of "l" System.out.println("Second appearance of the letter 'l' is on index " + secondIndex); } }
У наведеному вище прикладі використано більш практичний підхід. Ми використали позицію першого входження вказаної літери, щоб шукати другу літеру, починаючи з індексу, збільшеного на 1. Таким чином, пошук починається з наступного індексу після індексу першого входження потрібної літери або набору літер.
Крім того, параметри String str
та int fromIndex
можна міняти місцями.
Також варто зазначити, що якщо метод indexOf()
не знаходить вказану літеру або набір літер, він повертає значення -1
. Наприклад:
Main.java
package com.example; // do not modify the code below this comment public class Main { public static void main(String[] args) { String hello = "Hello"; // find the index of the letter "d" in the string int index = hello.indexOf("d"); // output the index, if the specified letter is not found, the value will be -1 System.out.println("Value of index, if it does not find a specified letter: " + index); } }
Пошук літери "d"
у рядку "Hello"
не дав результатів, і метод повернув -1
. Це може бути корисним для встановлення умов або створення точки виходу з циклу.
Як знайти останній індекс у рядку
У класі String
також є метод, який дозволяє здійснювати пошук з кінця рядка. Цей метод називається lastIndexOf()
. Він працює за тим самим принципом. Розглянемо приклад знаходження останнього входження літери "l"
у рядку "Hello"
:
Main.java
package com.example; // do not modify the code below this comment public class Main { public static void main(String[] args) { String hello = "Hello"; // find the last index of the letter "l" int lastIndex = hello.lastIndexOf("l"); // output the last index where the letter "l" appears System.out.println("Last index of the letter 'l' : " + lastIndex); } }
У цьому випадку ми отримали результат 3
, що відповідає індексу останнього входження літери "l"
.
Дякуємо за ваш відгук!