Get string character by index
In Java, you can get a character at a specific index in a string using the charAt()
method of the String
class. This method takes an index as an argument and returns the character at that index.
For example:
String str = "hello";
char c = str.charAt(0); // c will be 'h'
Note that the index of the first character in the string is 0, and the index of the last character is string.length() - 1
.
If you try to access an index that is out of bounds (i.e., less than 0 or greater than or equal to the length of the string), the charAt()
method will throw an IndexOutOfBoundsException
.
You can also use the toCharArray()
method to convert a string to an array of characters and then access the character at a specific index:
String str = "hello";
char[] chars = str.toCharArray();
char c = chars[0]; // c will be 'h'
Alternatively, you can use the substring()
method to get a substring of the string and then access the first character of the substring:
String str = "hello";
String sub = str.substring(0, 1);
char c = sub.charAt(0); // c will be 'h'