0

In Java, I want to extract the differences from one comma-separated string when compared to another.

e.g

The string I want to extract the differences from: 1,hello,fire,dog,green

The string I am comparing with : 1,hello,water,dog,yellow

So the result of the function would give me a arraylist of [3,fire] and[5,green] as those items are different than the items in the second string, which are 'water' and 'yellow'. The numbers are the index positions of each item detected to be a difference. The other items match and are not considered.

unwind
  • 391,730
  • 64
  • 469
  • 606
MisterIbbs
  • 247
  • 1
  • 7
  • 20

3 Answers3

1

First, you can create your own Pair class (based on Creating a list of pairs in java), doesn't have to be template.

Then Do something like this:

Split the two strings:

List<String> toCompareSplit= Arrays.asList(toCompare.split(","));
List<String> compareWithSplit= Arrays.asList(compareWith.split(","));

Iterate the lists:

List<Pair> diffList= new ArrayList<Pair>(); 
for (int i= 0; i < toCompareSplit.size; i++){
    if (!toCompareSplit.get(i).equals(compareWithSplit.get(i))){
        Pair pair= new Pair(i+1, toCompareSplit.get(i));
        diffList.add(pair);
    }
}

If the lists aren't in the same size you can run to the end of the shortest one etc.

Community
  • 1
  • 1
user265732
  • 585
  • 4
  • 14
0
var left = "1,hello,fire,dog,green";
var right = "1,hello,water,dog,yellow";
var result = left.Split(',').Zip(right.Split(','), Tuple.Create).Where(x => x.Item1 != x.Item2).ToArray();

Using C#, this will return an array of tuples of the different elements. Sorry I don't have a compiler to hand so may be some small syntax errors in there.

Jon G
  • 4,083
  • 22
  • 27
0

Why not just loop through by splitting the strings.

public static List<String> compareStrings(String str1, String str2) { String[] arrStr1 = str1.split(","); String[] arrStr2 = str2.split(","); List<String> strList = new ArrayList<String>(); for(int index = 0; index < arrStr1.length; ++index) { if (!arrStr1[index].equals(arrStr2[index])) { strList.add("[" + index + "," + arrStr1[index] + "]"); } } return strList; }

Beaware of index out of bounds exception..!!

Xavier DSouza
  • 2,861
  • 7
  • 29
  • 40
  • Wow, that is pretty simple, not sure how i didn't think of it. Thanks for your help. Ill use this approach. – MisterIbbs Oct 07 '14 at 13:09