English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
O método charAt() da String Java retorna o caractere na posição especificada.
A sintaxe do método charAt() da String Java é:
string.charAt(int index)
index - Índice do caractere (valor int)
Retorna o caractere na posição especificada (index)
Note:If the index passed to charAt() is negative or out of range, an exception will be thrown.
class Main { public static void main(String[] args) { String str1 = "Learn Java"; String str2 = "Learn\nJava"; //first character System.out.println(str1).charAt(0)); // 'L' //seventh character System.out.println(str1.charAt(6)); // 'J' //sixth character System.out.println(str2.charAt(5)); // '\n' } }
In Java, the index of a string starts from 0, not1. This is why charAt(0) returns the first character. Similarly, charAt(5) and charAt(6) returns the sixth and seventh characters.
To find the index of the first occurrence of a specified character, useJava String indexOf()Methods.