English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La méthode Java String charAt() retourne le caractère à l'indice spécifié.
La syntaxe de la méthode string.charAt() de Java :
string.charAt(int index)
index - Index du caractère (valeur int)
Renvoie le caractère à l'indice spécifié (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"; //the first character System.out.println(str1).charAt(0)); // 'L' //the seventh character System.out.println(str1.charAt(6)); // 'J' //the 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) to return the sixth and seventh characters.
If you need to find the index of the first occurrence of a specified character, please useJava String indexOf()methods.