+92 332 4229 857 99ProjectIdeas@Gmail.com

How to extract matching strings from two string arrays (Java)



How to extract matching strings from two string arrays (Java):

You have the following two string arrays and you want extract the matching strings from both.  In this particular example “i”, “am” and “osama” are same in both strings.

String[] str1 = new String[] {"i","am","osama","maverick"};  
String[] str2 = new String[] {"osama","am","mascot","stunned","I"};

Code


for (int i = 0 ; i < str1.length ; i++) {
             
     for (int j = 0 ; j < str2.length ; j++) {
                          
Here, checking each string from str1 to str2 then ignoring case display those strings which match each other , if you see in str1 "i" is small and in str2 "I" is capital, so that's why we put equalsIgnoreCase() function here, but if we put just equals() function here then the output would be "am osama":

           if (str1[i].equalsIgnoreCase(str2[j])) {
                          
                 System.out.println(str1[i]);
           }
     }
}

Output of the program is:

      i
      am
      osama

0 comments: