Posted By: Anonymous
I know how to work out the index of a certain character or number in a string, but is there any predefined method I can use to give me the character at the nth position? So in the string “foo”, if I asked for the character with index 0 it would return “f”.
Note – in the above question, by “character” I don’t mean the char data type, but a letter or number in a string. The important thing here is that I don’t receive a char when the method is invoked, but a string (of length 1). And I know about the substring() method, but I was wondering if there was a neater way.
The method you’re looking for is
charAt. Here’s an example:
String text = "foo"; char charAtZero = text.charAt(0); System.out.println(charAtZero); // Prints f
If you don’t want the result as a
char data type, but rather as a string, you would use the
String text = "foo"; String letter = Character.toString(text.charAt(0)); System.out.println(letter); // Prints f
If you want more information on the
Character class and the
toString method, I pulled my info from the documentation on Character.toString.