English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Contrôle de flux Java

Java Tableau

Java Programmation orientée objet (I)

Java Programmation orientée objet (II)

Java Programmation orientée objet (III)

Gestion des exceptions Java

Java Liste (List)

Java Queue (file d'attente)

Java Map collection

Java Set collection

Java Entrée/Sortie (I/O)

Java Reader/Writer

Autres sujets Java

Méthode et exemple d'utilisation de Java String charAt()

Java String (string) methods

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)

Paramètre de charAt()

  • index - Index du caractère (valeur int)

Valeur retournée par charAt()

  • 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.

Example: Java String charAt() method

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.

Java String (string) methods