charAt
A string is backed by an array of characters, but you can’t access a character in a string by using
array notations ( [i] ). Instead, you need to use the charAt command. This returns the
character at a particular index in the string. Like an array, the first index in a string is 0, and the
last one is the length-1. Here’s an example:
String s = "Hello";
//has value e
char c = s.charAt(1); Now that we know the length and charAt commands, we can step through every character in
a string. Here’s an example that prints every character in a string:
Scanner s = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = s.nextLine();
for (int i = 0; i < str.length(); i++)
{
System.out.printf("Character: %c%n", str.charAt(i));
}