Get string character by index - Java


You want .charAt()

Here's a tutorial


returns s

If you're hellbent on having a string there are a couple of ways to convert a char to a string:

String mychar = Character.toString("mystring".charAt(2));


String mychar = ""+"mystring".charAt(2);

Or even

String mychar = String.valueOf("mystring".charAt(2));

For example.


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.

Here's the correct code. If you're using zybooks this will answer all the problems.

for (int i = 0; i<passCode.length(); i++)
    char letter = passCode.charAt(i);
    if (letter == ' ' )
        System.out.println("Space at " + i);

A hybrid approach combining charAt with your requirement of not getting char could be

newstring = String.valueOf("foo".charAt(0));

But that's not really "neater" than substring() to be honest.



java java   string