Nikhil Kumar Nikhil Kumar - 7 months ago 12
Java Question

Find index of item in array entered by user

I have a edittext and allows user to enter the items.

`EditText editText=(EditText)findViewById(R.id.edit);

String s=editText.getText().toString();

String [] array= s.split("\");`


Suppose user entered
D\A\E\B
. Now I want to find the
index
of third item entered by user (which is E here ) .

How to find the index of third item ?

Answer

Here it is:

EditText editText=(EditText)findViewById(R.id.edit);

String str = "E";  // string you search for

String s=editText.getText().toString();

String [] array= s.split("\");
int index = -1;

for (int i = 0; i < array.length; i++) {
    if (array[i].equals(str)) { // use equals, not ==
         index = i;
         break;
    }
}

So, if index is -1, there is no str in user input array. If it is bigger then -1, you get the index. (break is there so you don't need to continue trough array since you find the index).