Méthode Java String charAt()
La chaîne Java charAt() renvoie la valeur char (caractère) au numéro d'index spécifié. La valeur de l'index doit être comprise entre 0 et (longueur de chaîne-1) ; sinon, la méthode lèvera IndexOutOfBoundsException .
Par exemple, charAt(1) renverra le deuxième caractère de la chaîne et charAt(0) renverra le premier caractère de la chaîne.
Syntaxe :
public char charAt(int index)
Paramètre
La chaîne Java charAt() la méthode ne prend qu'un seul paramètre, c'est-à-dire la valeur de l'index.
Paramètre | Type | Description |
index (obligatoire) | entier | spécifie la position du caractère à renvoyer par la méthode. |
Valeur de retour
La chaîne Java charAt() renvoie la valeur char de l'index spécifié.
Exception :
La méthode Java String charAt() lève une StringIndexOutOfBoundsException exception si la valeur de l'index est inférieure supérieur à 0 (négatif) ou supérieur à la longueur de la chaîne.
charAt() lance une exception StringIndexOutOfBounds
//IndexOutOfBoundsException
//Main class of the program
public class Main {
//Main method of the program
public static void main (String[] args) {
//String type variable
String stechiesTitle = "STechies - Free Taraining Tutorials for Techie";
//Variable to hold the number of counts of occurrence of character
int count = 0;
//For Loop of the iteration
//For Loop will run equal to string length times + 1 times
for(int i = 0; i < stechiesTitle.length()+1; i++){
//storing the character in a temporary variable
char x = stechiesTitle.charAt(i);
//checking,Is character is equals to `s`
if(x == 's'){
//Increasing the count on each occurrence
count++;
}
}
//Printing the output
System.out.println("s occurred "+count+" time in this string");
}
}
Sortie
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 8
at java.lang.String.charAt(String.java:658)
at Main.main(Main.java:10)