У меня есть функция, которая сравнивает 2 строки и распечатывает, сколько общих элементов. Мой текущий код:
public void StringCheck(String one, String two) {
String[] subStrings1 = one.split(", ");
String[] subStrings2 = two.split(", ");
Set<String> set1 = new HashSet<>();
Set<String> set2 = new HashSet<>();
for (String s : subStrings1) {
set1.add(s);
}
for (String s : subStrings2) {
set2.add(s);
}
set1.retainAll(set2);
textView3.setText(set1.size() + "");
}
Когда я вызываю такую функцию: StringCheck("1, 2, 3, 4, 5" , "1, 2, 3, 4 ,5");, она выводит 5 на моем экране Android.
Но на самом деле я хочу сравнить свою первую строку с другими строками. Например, я хочу указать одну строку и один массив строк в качестве параметров и посмотреть, сколько элементов является общим.
Предположим, что моя первая строка: "1, 2, 3, 4, 5" Я хочу сравнить ее с другими. Скажем,
второй "2, 3, 4, 5, 6"
третий "3, 4, 5, 6, 7"
Я хочу, чтобы результат был таким:
Result 1: 4 Result 2: 3




Это немного грубо, но это должно сработать:
public void StringCheck(String one, String[] two) {
String result = "";
String[] subStrings1 = one.split(", ");
Set<String> set1 = new HashSet<>();
// Add all the targets to a set
for(String s: subStrings1)
{
set1.add(s);
}
// For each of the input strings in the array
for(int i = 0; i < two.length; ++i)
{
// Keep track of the total, and split based on the comma
int total = 0;
String[] subStrings2 = two[i].split(", ");
// For each of the substrings
for(String s2: subStrings2)
{
// If the set contains that substring, increment
if (set1.contains(s2))
{
++total;
}
}
// Format result string
result += "Result " + (i+1) + ":" + total + " ";
}
//Set the text view
textView3.setText(result);
}
Ваш реальный код работает для одного сравнения. Почему бы просто не извлечь часть, которая подсчитывает количество пересечений, в метод и вызывать его для каждого сравнения, которое вы хотите выполнить?
public int countNbIntersection(String one, String two) {
String[] subStrings1 = one.split(", ");
String[] subStrings2 = two.split(", ");
Set<String> set1 = new HashSet<>();
Set<String> set2 = new HashSet<>();
for (String s : subStrings1) {
set1.add(s);
}
for (String s : subStrings2) {
set2.add(s);
}
set1.retainAll(set2);
return set1.size();
}
Вы можете вызвать его и выдать ожидаемое сообщение:
String reference = "1, 2, 3, 4, 5";
String other = "2, 3, 4, 5, 6";
String other2 = "3, 4, 5, 6, 7";
String firstCount = "Result 1 " + countNbIntersection(reference, other);
String secondCount = "Result 2 " +countNbIntersection(reference, other2);
String msg = firstCount + " " + secondCount;
Пожалуйста, попробуйте этот код с вводом: StringCheck("1, 2, 3, 4, 5" , new String[]{"1, 5","1, 2, 3, 4, 5","7"});
public static void StringCheck(String one, String []two){
String[] numbersOne = one.split(", ");//1 2 3 4 5
String result = "";
for (int i = 0; i < two.length; i++) {
int counter = 0;
String [] numbersTwo = two[i].split(", ");//2 3 4 5 6
for (int j = 0; j < numbersTwo.length; j++) {
for (int k = 0; k < numbersOne.length; k++) {
if (numbersTwo[j].equals(numbersOne[k])){
counter++;
break;
}
}
}
result+ = "Result "+(i+1)+":"+counter+" ";
}
textView3.setText(result);
}
Результат будет: Result 1:2 Result 2:5 Result 3:0