4

Let's say I have an array like this:

String[] = {
    "#abc #def",
    "#abc",
    "#def",
    "#xyz #def"
}

My question is I want to search for specific character or string like "#abc" or "a" and get their positions in the array.

5 Answers 5

8

Just loop through it and check each string yourself

for(int i=0; i < array.length; i++)
    if(array[i].contains("#abc"))
        aPosition = i;

If you want to store multiple positions, you'll need a mutable array of some sort such as a List, so instead of aPosition = i you'll have list.add(i)

Sign up to request clarification or add additional context in comments.

3 Comments

That doesn't answer my question then. That's what I needed. To store all positions in an array
that list.add(i) seems to be pretty good thing. Gimme a sec to test it. And yes, I know Java but this isn't thing I am very familiar with
Basically I found out that putting the values into the list isn't neccessary because I wanted just to put the values into listview.
7
String[] values = { "1a", "2a", "3a"};
int pos = new ArrayList<String>(Arrays.asList(values)).indexOf("3a");

Comments

1
let's call your array of strings s, the code will be:
String[] s={"#abc #def",
            "#abc",
            "#def",
            "#xyz #def"};
int count=0;
    for(String s1:s){
if(s1.contains("#abc")){
//do what ever you want
System.out.println("Found at: "+count);
break;
}
count++;
}

hope this will work for you.

Comments

0

Use indexOf

String[] myList = {
            "#abc #def",
            "#abc",
            "#def",
            "#xyz #def"
           };
int index = myList.indexOf("#abc");

and in the index variable you become the index of the searched element in your array

3 Comments

yeah, that will return one number but I want all index nubers that have that string in them
"Cannot invoke indexOf(String) on the array type String[]"
indexOf doesn't exist
-1

you can use ArrayUtils

String[] myList = { "#abc #def", "#abc", "#def", "#xyz #def" };
int index =  ArrayUtils.indexOf(myList,"#def");

2 Comments

in this case using for loop is better solution because there are more indexes that have specific string not just one
and there doesn't appear to be a method .indexOf for ArrayUtils

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.