Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Метод indexof() | Рядки: Розширений Рівень
Java Extended
course content

Зміст курсу

Java Extended

Java Extended

1. Глибока Структура Java
2. Методи
3. Рядки: Розширений Рівень
4. Класи
5. Класи: Розширений Рівень

book
Метод indexof()

Як знайти індекс заданого символу у String?

Для знаходження індексу першого входження певної літери клас String надає метод indexOf(). Цей метод перевантажений і має декілька реалізацій. Розглянемо, що робить кожна з них:

indexOf(String str)

indexOf(String str) — у цьому методі параметр визначає, що саме ми шукаємо. Це може бути одна літера в подвійних лапках (""), послідовність літер або навіть слово. Метод повертає індекс першого входження вказаного параметра у рядку. Наприклад, знайдемо індекс літери "l" у рядку "Hello":

Main.java

Main.java

copy
12345678910111213
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

Main.java

copy
123456789101112131415
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

Main.java

copy
12345678910111213
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

Main.java

copy
12345678910111213
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".

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 4

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

course content

Зміст курсу

Java Extended

Java Extended

1. Глибока Структура Java
2. Методи
3. Рядки: Розширений Рівень
4. Класи
5. Класи: Розширений Рівень

book
Метод indexof()

Як знайти індекс заданого символу у String?

Для знаходження індексу першого входження певної літери клас String надає метод indexOf(). Цей метод перевантажений і має декілька реалізацій. Розглянемо, що робить кожна з них:

indexOf(String str)

indexOf(String str) — у цьому методі параметр визначає, що саме ми шукаємо. Це може бути одна літера в подвійних лапках (""), послідовність літер або навіть слово. Метод повертає індекс першого входження вказаного параметра у рядку. Наприклад, знайдемо індекс літери "l" у рядку "Hello":

Main.java

Main.java

copy
12345678910111213
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

Main.java

copy
123456789101112131415
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

Main.java

copy
12345678910111213
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

Main.java

copy
12345678910111213
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".

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 4
some-alt