0

How to get an index position of a char c in the array chars?.

public static final String[] chars = new String[]{"A","B","C","D","E","F"};
String c = "E";

// the answer is 4.
4
  • 1
    If your array is sorted, you can use Arrays.binarySearch(). Commented Mar 2, 2015 at 11:12
  • 2
    And if it's not, just use Arrays.asList(chars).indexOf(c) Commented Mar 2, 2015 at 11:15
  • @Florent Bayle: Yes, it's sorted. Could you please post an example? Commented Mar 2, 2015 at 11:15
  • is it an option to use a Set or List? Commented Mar 2, 2015 at 11:15

2 Answers 2

4

If your array is sorted, you can use

Arrays.binarySearch()

int answer = Arrays.binarySearch(chars, c);
return answer;

as was mentioned. Otherwise use a for loop.

for (int i=0; i<chars.length; ++i) {
   if (s[i].equals(c)) {
        return i;
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

looks like a solution
3

Here is the solution, hope this helps you

    String[] src = new String[]{"A","B","C","D","E","F"};
    int biggerWher = Arrays.asList(src).indexOf("E");
    System.out.println(biggerWher);

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.