Fadi A.
Fadi A.

Reputation: 93

Java/Android: how to find the first characters of a string if it equals other string

I have a String Array #1 countries[] and I have another String Array #2 splitr_str[] that have the same values but it split in half.

What I want is to to check which value of the #2 Array match the first half value of the #1 String Array which has the full word.

Here's an example:

String[] countries = new String[]{"USA", "Spain" ,"Germany"};

String[] split_str = new String[]{"Sp", "ain", "A" ,"US" ,"Ger", "ma","ny"};

Now i want to detect only the first half of the countries values that match the ssplit_str value

for USA i just want to pick "US" which is in

 split_str[3]

and if i found it ? i pick "A" which is

 split_str[2]

And so on.

Any ideas on how to do that?

Upvotes: 1

Views: 85

Answers (2)

Keara
Keara

Reputation: 620

Try using for loops. As I just learned from this post, you an use a label and break to easily break out of both loops once the match has been found.

outerloop:
for( String country : countries){
     for( String segment : split_str) {
        if( country.startsWith( segment ) ) {
            // do something here when the segment has been detected
            break outerloop;
        }
     }
}

Upvotes: 1

Aayush Gupta
Aayush Gupta

Reputation: 55

I know its a bit inefficient. But its the best solution I could find

    for (int i = 0; i < countries.length; i++)
    {
        for(int j = 0; j < split_str.length; j++)
        {
            if(countries[i].substring(0, (countries[i].length() / 2) + 1).contains(split_str[j]))
            {
                for (int k = 0; k < split_str.length; k++)
                {
                    if (countries[i].substring((countries[i].length() / 2) + 1, countries[i].length()).contains(split_str[k]))
                    {
                        System.out.println(i);
                    }
                }
            }
        }
    }

Hope it helps!

Upvotes: 0

Related Questions