1

I have a string array which looks like:

String[] rows = {"AAA","BBB","CCC"};

How can I get a specific index of a certain row? If I do rows[6] i get an out of bounds ex. However when I do rows[2] i get the entire CCC string.

Do I have to get the row first, then get a specific char? Or can I not just grab it from the array?

3
  • What did you expect rows[6] to return? You've got an array of strings - so when you access that array by index, you do indeed get the whole string - and then you can get the character within that string using charAt. Commented Feb 27, 2015 at 20:56
  • I expected it to return B. But seeing as its an array, that was silly to think it would return a single letter... Commented Feb 27, 2015 at 20:57
  • @ThatGuy343 Java has 0-indexed arrays, like most programming languages. Even if the array worked as you expected it to, it would have returned 'C'. Commented Feb 27, 2015 at 20:58

3 Answers 3

4

Use String#charAt(int index) to get the character at the desired index after retrieving the string element, e.g.:

String[] rows = {"AAA","BBB","CCC"};
System.out.println(rows[2].charAt(2));   // C

If you want to (and if you really have to), you can concatenate all elements using a StringBuilder so that the result is AAABBBCCC, and use StringBuilder#charAt(int index):

String[] rows = {"AAA","BBB","CCC"};
StringBuilder sb = new StringBuilder();
for(String row : rows) {
    sb.append(row);
}
System.out.println(sb.charAt(6));  // C
Sign up to request clarification or add additional context in comments.

Comments

1
String[] rows = {"AAA","BBB","CCC"};

is a way of initializing your array with 3 elements at index 0,1 and 2(length 3). So you have to get your String first and you can use chatAt(position).

Comments

0
rows[1].charAt(2) // B
rows[0].charAt(0) // A

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.