cyorkston
cyorkston

Reputation: 235

Remove common words in two strings

Using APEX I have two strings and would like to remove common words in both from each string.

String s1 = 'this and1 this is a string1';
String s2 = 'this and2 this is a string2';

So that the result would be:

s1 = 'and1 string1';
s2 = 'and2 string2';

I started out by putting each string in a list:

List<String> strList1 = s1.split(' ');
List<String> strList2 = s2.split(' ');

Unfortunately removeAll() is not a list method in apex, so I can't perform:

strList1.removeAll(strList2);
strList2.removeAll(strList1);

Any ideas? Would using sets solve my issue?

Upvotes: 0

Views: 2125

Answers (3)

Ralph Callaway
Ralph Callaway

Reputation: 1848

You've got the right idea, but just need to convert your lists to sets so you can make use of the apex removeAll() function.

Set<String> stringSet1 = new Set<String>();
stringSet1.addAll(stringList1);
Set<String> stringSet2 = new Set<String>();
stringSet2.addAll(stringList2);

Then you can use the remove all function (keep a copy of stringSet1 since you're modifying it and want to use the original to remove from string set 2)

Set<String> originalStringSet1 = stringSet1.clone();
stringSet1.removeAll(stringSet2);
stringSet2.removeAll(originalStringSet1);

After you've done that you can iterate over your string list and build the string back up with all the words that weren't common between the strings.

Upvotes: 1

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28990

Try with this code

String s1 = "this and1 this is a string1"; String s2 = "this and2 this is a string2";

        List<String> strList1 = s1.Split(' ').ToList();
        List<String> strList2 = s2.Split(' ').ToList();

        var intersection = strList1.Intersect(strList2);
        foreach (var item in intersection.ToList())
        {
            strList1.RemoveAll(p => p.Equals(item));
            strList2.RemoveAll(p => p.Equals(item));
        }

Upvotes: 0

alaster
alaster

Reputation: 4171

You can rewrite your Strings:

Iterate through words and if you have different words just add them to the end of new strings

    // inside loop
    if (!word1.equals(word2)) {
        str1new += word1;
        str2new += word2;
    }

// outside of loop
s1 = str1new;
s2 = str2new;

Of course you need to add spaces between words. And how do you expect your program will work with strings with differ length?

Upvotes: 0

Related Questions