java多字符串数组比较

时间:2014-05-26 12:39:13

标签: java arrays compare

我有9个字符串数组,我已从文件中读取。其中一个数组(main)将分别与其他数组进行比较。阵列具有不同的长度。 我写了一个匹配函数,检查每个新闻项等于其他数组项。如果匹配,则写入数组的标签。如果没有匹配,那么" / o"打印出来。 问题是每个阵列有8个函数,我想降低复杂性并在一个函数中完成。我怎么能实现它?我的示例代码是: 该示例仅适用于arr1,因此我需要为其他数组写入7次。

String[] main = "g, a1, c1, r,..."
String[] arr1 = "a1, b1, c1"
String[] arr2 = "e, r, g" 
String[] arr3 = "g, m, l, x"
String[] arr4 = "s, b, l"
String[] arr5 = "a, f, o, t, e"
String[] arr5 = "g, h, j"
String[] arr5 = "q, b"
String[] arr5 = "z, v, n"


for (int j = 0; j < main.length; j++) { 
   for (int i = 0; i < arr1.length; i++){
   int varLength = arr1[i].length();
   for (int e = 3; e < varLength; e++) {  // substring is done by 3 
           String substr1 = arr1[i].substring(0, e)
          if (substr1.equalsIgnoreCase(main[j]))   
             {
    main[j] = main[j] + "/arr1";
             }
       }
   }
}


Expected Output : 
arr1 = "g/O, a1/arr1, c1/arr1, r/O"
arr2 = "e/O, r/arr2, g/arr2 "
arr3 = "g/arr3, m/O, l/O, x/O"  And goes like this for the other arrays

2 个答案:

答案 0 :(得分:0)

简单地循环所有数组:

// Create an array containing your 7 arrays
String[][] allArrays = new String[][] {arr1, arr2, arr3, arr4, arr5, arr6, arr7};
int counter = 1;
for(String[] arr : allArrays) {
    for (int j = 0; j < main.length; j++) { 
        for (int i = 0; i < arr.length; i++){
            // do as before
            main[j] = main[j] + "/arr" + counter++;
            // ...
        }
    }
}

答案 1 :(得分:0)

实现这一目标的一种方法是

  public static matcher(String[] main, String[] toMatch, String arrayName) {
    for(String curr : main) {
        String toAppend = "/0";
        for(String matchAgains : toMatch) {
            for (int e = 3; e < varLength; e++) {  // substring is done by 3 
               String substr1 = curr.substring(0, e)    
               if(substr1.equalsIgnoreCase(matchAgainst)) {
                    toAppend = arrayName;
               }
            }
        }
        System.out.println(main+"/"+toAppend);
    }
} 

使用像这样的函数你可以调用matcher(main,arr1,"arr1");,否则如果你正在寻找完整的匹配(不仅仅是子字符串),你可以使用集合,你可以做(​​这是我的初始想,但我误解了这个问题)

public static matcher(Set<String> main, Set<String> toMatch, String arrayName) {
    for(String curr : main) {
        String toAppend = "/0";
        if(toMatch.contains(main)) {
            toAppend=arrayName;
        }

        System.out.println(main+"/"+arrayName);
    }
}