这是我的第一个问题,是关于 Java 的。 我想实现以下逻辑:
I have got two string Arrays(or string Lists of string). There is an array of strings (asu) - M1, M2, M3 ... As well as an array of string (rzs) - M1, M2, M3 and all possible combinations thereof. The need for each element (asu) (for example M1) to find an element in (rzs) (M1, M1M2, ..), which contains (e.g. M1). Example: took M1 from (asu) and will start search for duplicate(contain) in (rzs). We found M1M2 in (rzs), it contains M1. After that we should delete both elements from arrays(lists). And I'm sorry for my English skills^^
String[] asu = { "M1", "M1", "M1", "M3", "M4", "M5", "M1", "M1", "M1", "M4", "M5", "M5" };
String[] rzs = { "M1", "M2", "M3", "M4", "M5", "M1M2", "M1M3", "M1M4", "M1M5", "M2M3", "M2M4", "M2M5", "M3M4", "M3M5", "M4M5", "M1M2M3", "M1M2M4",
"M1M2M5", "M1M3M4", "M1M3M4", "M1M4M5", "M2M4", "M2M5" };
public static void main(final String[] args) {
work bebebe = new work();
bebebe.mywork();
}
public void mywork() {
System.out.println(Arrays.deepToString(rzs));
System.out.println(Arrays.deepToString(asu));
for (int i = 0; i < asu.length; i++) {
System.out.println("Итерация: " + i);
for (int j = 0; j < rzs.length; j++) {
if (asu[i].matches(rzs[j].toString())) {
System.out.println(i + " элемент (" + asu[i] + ") в ASU равен " + j + " элементу (" + rzs[j] + ") в RZS");
asu[i] = "";
rzs[j] = "";
}
}
}
}
The result does not delete items that are substring. Does not satisfy logic. I will appreciate your advice.
最佳答案
如果你使用列表,你会得到更好的结果: 删除不会要求您取回数组的其余部分,并且使用列表意味着代码中的逻辑更少
List<string> asu = Arrays.asList("M1","M1","M1","M3","M4","M5","M1","M1","M1","M4","M5","M5");
List<string> rzs = Arrays.asList("M1","M2","M3","M4","M5",
"M1M2","M1M3","M1M4","M1M5","M2M3","M2M4","M2M5","M3M4","M3M5","M4M5"
,"M1M2M3","M1M2M4","M1M2M5","M1M3M4","M1M3M4","M1M4M5","M2M4","M2M5");
public static void main(String[] args) {
work bebebe = new work();
bebebe.mywork();
}
public static void mywork() {
ArrayList<String> tmp1 = new ArrayList<String>();
ArrayList<String> tmp2 = new ArrayList<String>();
System.out.println((rzs));
System.out.println((asu));
for (String curr : asu){
for (String currRzs : rzs){
if (currRzs.contains(curr)) {
System.out.println(" item("+curr+") in ASU found contained in ("+currRzs+") in RZS");
if(tmp1.contains(curr) == false)
tmp1.add(curr);
if(tmp2.contains(currRzs) == false)
tmp2.add(currRzs);
}
}
}
for (String curr : tmp1){
asu.remove(curr);
}
for (String curr : tmp2){
rzs.remove(curr);
}
}
关于 java 。如何从两个字符串数组或列表中删除相同的字符串对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18051996/