What is the usage of the charAt function in Java?

In Java, the charAt() function is used to retrieve a character at a specified position in a string.

Its syntax is:

char charAt(int index)

The index parameter indicates the position of the character to be retrieved, starting from 0. If the specified position is beyond the length of the string, a StringIndexOutOfBoundsException will be thrown.

This is an example:

String str = "Hello World";
char ch = str.charAt(6);
System.out.println(ch);  // 输出 'W'

In the example above, charAt(6) will return the character at index 6 in the string, which is ‘W’.

bannerAds