Search code examples
javastringsearchsplitchars

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?


Solution

  • 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;
            }
         }
    }