3

Hello I need to get a char's index form a char array (By not using String). Yes I know it is unreasonable to do it while there is String but I need to know how to do it. So, I would appreciate that if you could show understanding.

My char array holds:

" ABCDEF"

(It has a space at the beginning).

When I try this: (I have already imported java.util.Arrays;)

Arrays.toString(charArr).indexOf(charNeeded);

It returns 16 because:

System.out.println(Arrays.toString(charArr));

Prints [ , A, B, C, D, E, F], it means the String that is being returned(index being searched in) is that. I need to search the index on " ABCDEF" can anyone help?

Thanks in advance.

2
  • 1
    Possible duplicate of Where is Java's Array indexOf? Commented Jun 5, 2018 at 8:36
  • instead of using Arrays.toString(charArr).indexOf(charNeeded); use new String(charArr).indexOf(charNeeded); Commented Jun 5, 2018 at 8:39

1 Answer 1

8

If you can't convert it to a string and use indexOf:

int found = new String(charArr).indexOf(charNeeded)

then you would need to use a loop:

int found = -1;
for (int i = 0; i < charArr.length; ++i) {
  if (charArr[i] == charNeeded) {
    found = i;
    break;
  }
}

Or, if you want to use a very over-the-top solution, using streams:

int found =
    IntStream.range(0, charArr.length)
        .filter(i -> charArr[i] == charNeeded)
        .findFirst()
        .orElse(-1);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your understanding and kinid answer I think this would work.

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.