Método indexof()
Como Encontrar o Índice de um Caractere Específico em uma String
Para localizar o índice da primeira ocorrência de uma letra específica, a classe String
oferece o método indexOf()
. Este método é sobrecarga e possui várias implementações. Veja o que cada uma faz:
indexOf(String str)
indexOf(String str)
– neste método, o parâmetro especifica o que está sendo buscado. Pode ser uma única letra entre aspas duplas (""
), uma sequência de letras ou até mesmo uma palavra. Este método retorna o índice da primeira ocorrência do parâmetro especificado na string. Por exemplo, vamos encontrar o índice da letra "l"
na string "Hello"
:
Main.java
12345678910111213package 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); } }
No exemplo acima, a variável index
foi inicializada utilizando o método indexOf("l")
. Agora, essa variável contém o índice da primeira ocorrência da letra "l"
na string "Hello"
.
indexOf(String str, int fromIndex)
indexOf(String str, int fromIndex)
– o primeiro parâmetro é igual ao anterior, especificando o que está sendo buscado.
O segundo parâmetro determina o índice inicial a partir do qual a busca será realizada. Por exemplo, na palavra "Hello"
, há 2 ocorrências da letra "l"
, e queremos encontrar o índice da segunda ocorrência. Pelo primeiro exemplo, sabemos que a primeira ocorrência está no índice 2
, então vamos definir o parâmetro fromIndex
como 3 e encontrar o índice do segundo "l"
:
Main.java
123456789101112131415package 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); } }
No exemplo acima, foi adotada uma abordagem mais prática. Utilizou-se a localização da primeira ocorrência da letra especificada para buscar a segunda letra a partir do índice incrementado em 1. Dessa forma, a busca começa no próximo índice após o índice da primeira ocorrência da letra ou conjunto de letras desejado.
Além disso, os parâmetros String str
e int fromIndex
podem ser alternados.
Também é importante observar que, se o método indexOf()
não encontrar a letra ou conjunto de letras especificado, ele retornará o valor -1
. Por exemplo:
Main.java
12345678910111213package 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); } }
A busca pela letra "d"
na string "Hello"
não retornou nenhum resultado, e o método retornou -1
. Isso pode ser útil para definir condições ou criar um ponto de saída em um loop.
Como Encontrar o Último Índice na String
A classe String
também possui um método que permite a busca a partir do final da string. Esse método é chamado de lastIndexOf()
. Ele opera sob o mesmo princípio. Vamos analisar um exemplo de como encontrar a última ocorrência da letra "l"
na string "Hello"
:
Main.java
12345678910111213package 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); } }
Aqui, obtivemos o resultado 3
, que representa o índice da última ocorrência da letra "l"
.
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Can you show an example of using indexOf() with a substring instead of a single character?
How does lastIndexOf() work with substrings?
What happens if the character or substring is not found in the string?
Awesome!
Completion rate improved to 2.63
Método indexof()
Deslize para mostrar o menu
Como Encontrar o Índice de um Caractere Específico em uma String
Para localizar o índice da primeira ocorrência de uma letra específica, a classe String
oferece o método indexOf()
. Este método é sobrecarga e possui várias implementações. Veja o que cada uma faz:
indexOf(String str)
indexOf(String str)
– neste método, o parâmetro especifica o que está sendo buscado. Pode ser uma única letra entre aspas duplas (""
), uma sequência de letras ou até mesmo uma palavra. Este método retorna o índice da primeira ocorrência do parâmetro especificado na string. Por exemplo, vamos encontrar o índice da letra "l"
na string "Hello"
:
Main.java
12345678910111213package 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); } }
No exemplo acima, a variável index
foi inicializada utilizando o método indexOf("l")
. Agora, essa variável contém o índice da primeira ocorrência da letra "l"
na string "Hello"
.
indexOf(String str, int fromIndex)
indexOf(String str, int fromIndex)
– o primeiro parâmetro é igual ao anterior, especificando o que está sendo buscado.
O segundo parâmetro determina o índice inicial a partir do qual a busca será realizada. Por exemplo, na palavra "Hello"
, há 2 ocorrências da letra "l"
, e queremos encontrar o índice da segunda ocorrência. Pelo primeiro exemplo, sabemos que a primeira ocorrência está no índice 2
, então vamos definir o parâmetro fromIndex
como 3 e encontrar o índice do segundo "l"
:
Main.java
123456789101112131415package 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); } }
No exemplo acima, foi adotada uma abordagem mais prática. Utilizou-se a localização da primeira ocorrência da letra especificada para buscar a segunda letra a partir do índice incrementado em 1. Dessa forma, a busca começa no próximo índice após o índice da primeira ocorrência da letra ou conjunto de letras desejado.
Além disso, os parâmetros String str
e int fromIndex
podem ser alternados.
Também é importante observar que, se o método indexOf()
não encontrar a letra ou conjunto de letras especificado, ele retornará o valor -1
. Por exemplo:
Main.java
12345678910111213package 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); } }
A busca pela letra "d"
na string "Hello"
não retornou nenhum resultado, e o método retornou -1
. Isso pode ser útil para definir condições ou criar um ponto de saída em um loop.
Como Encontrar o Último Índice na String
A classe String
também possui um método que permite a busca a partir do final da string. Esse método é chamado de lastIndexOf()
. Ele opera sob o mesmo princípio. Vamos analisar um exemplo de como encontrar a última ocorrência da letra "l"
na string "Hello"
:
Main.java
12345678910111213package 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); } }
Aqui, obtivemos o resultado 3
, que representa o índice da última ocorrência da letra "l"
.
Obrigado pelo seu feedback!