Salesforce 删除两个字符串中的常用词

Salesforce 删除两个字符串中的常用词,salesforce,apex-code,Salesforce,Apex Code,使用APEX,我有两个字符串,希望从每个字符串中删除这两个字符串中的常用词 String s1 = 'this and1 this is a string1'; String s2 = 'this and2 this is a string2'; 因此,结果将是: s1 = 'and1 string1'; s2 = 'and2 string2'; 我首先将每个字符串放在一个列表中: List<String> strList1 = s1.split(' '); List<St

使用APEX,我有两个字符串,希望从每个字符串中删除这两个字符串中的常用词

String s1 = 'this and1 this is a string1';
String s2 = 'this and2 this is a string2';
因此,结果将是:

s1 = 'and1 string1';
s2 = 'and2 string2';
我首先将每个字符串放在一个列表中:

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

有什么想法吗?使用集合可以解决我的问题吗?

您可以重写字符串:

遍历单词,如果您有不同的单词,只需将它们添加到新字符串的末尾

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

// outside of loop
s1 = str1new;
s2 = str2new;
当然,您需要在单词之间添加空格。您希望您的程序如何处理长度不同的字符串?

请尝试使用此代码

String s1=“this and 1 this is a string1”; String s2=“this and 2 this is a string2”

List strList1=s1.Split(“”).ToList();
List strList2=s2.Split(“”).ToList();
var intersection=strList1.Intersect(strList2);
foreach(intersection.ToList()中的变量项)
{
strList1.移除所有(p=>p.Equals(项目));
strList2.RemoveAll(p=>p.Equals(item));
}

您的想法是正确的,但只需将列表转换为集合,就可以使用apex removeAll()函数

Set<String> stringSet1 = new Set<String>();
stringSet1.addAll(stringList1);
Set<String> stringSet2 = new Set<String>();
stringSet2.addAll(stringList2);
Set stringSet1=new Set();
stringSet1.addAll(stringList1);
Set stringSet2=新集合();
stringSet2.addAll(stringList2);
然后可以使用“全部删除”功能(保留stringSet1的副本,因为您正在修改它,并且希望使用原始文件从字符串集2删除)

Set originalStringSet1=stringSet1.clone();
stringSet1.移除所有(stringSet2);
stringSet2.移除所有(原始StringSet1);

完成此操作后,您可以迭代字符串列表,并使用字符串之间不常见的所有单词重新构建字符串。

看起来这会起作用,但我认为您需要一个临时变量,否则stringSet2将无法正确删除。{A,B,C}.removeAll({B,C,D})正确地将stringSet1缩减为A,但在下一步中,您将引用已经缩减的集合{B,C,D}.removeAll({A})。需要引用原始stringSet1,而不是简化的stringSet1。
        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));
        }
Set<String> stringSet1 = new Set<String>();
stringSet1.addAll(stringList1);
Set<String> stringSet2 = new Set<String>();
stringSet2.addAll(stringList2);
Set<String> originalStringSet1 = stringSet1.clone();
stringSet1.removeAll(stringSet2);
stringSet2.removeAll(originalStringSet1);