我想检查一个字符串是否包含另一个字符串中特定长度的char序列,例如
String user1_hobbies = "friends, cinema/outside"
String user2_hobbies = "outside, going out with friends"
boolean check;
if (user1_hobbies.contains(user2_hobbies)){
check = true;
} else
{check = false
}
ofc这个尝试不起作用,因为整个字符串必须包含整个char序列。我只是想检查,如果只有两个字符串的部分匹配...在这种情况下它将匹配因为"朋友"或"外面"匹配。
答案 0 :(得分:3)
根据@JBNizet的提示,您可以为这两个句子创建两组单词,然后检查两个集合之间的交集是否为非空:
Set<String> set1 = new HashSet<String>(Arrays.asList(user1_hobbies.split(" ")));
Set<String> set2 = new HashSet<String>(Arrays.asList(user2_hobbies.split(" ")));
set1.retainAll(set2);
if (set1.size() > 0) {
System.out.println("There was a match.");
}
else {
System.out.println("There were no matches.");
}
您可能希望首先删除可能包含的任何无关标点符号,例如逗号或斜杠。在您的实际问题中,还可能需要做更多的工作。
答案 1 :(得分:1)
我建议将个人用户的爱好保存为两组字符串。然后你可以很容易地找到交叉点(即常见的爱好,set1.retainAll(set2))
或在您的情况下,如果交集非空,则设置check = true!
这是上一篇文章的一个例子: 公共课测试{
public static void main(String... args){
Set<String> set1 = new HashSet<String>(Arrays.asList("hobby1", "hobby2", "hobby3"));
Set<String> set2 = new HashSet<String>(Arrays.asList("hobby4", "hobby1", "hobby5", "hobby6"));
Set<String> intersection = new HashSet<String>(set1);
intersection = intersection.retainAll(set2);
System.out.println(intersection);
}
答案 2 :(得分:-1)
您可以使用拆分功能将字符串转换为数组,然后像这样检查...
String[] array_user1_hobbies = user1_hobbies.split(" ");
String[] array_user2_hobbies = user2_hobbies.split(" ");
ArrayList<String> a1 = new ArrayList<String>(Arrays.asList(array_user1_hobbies));
ArrayList<String> a2 = new ArrayList<String>(Arrays.asList(array_user2_hobbies));
boolean matches = (a1.retainAll(a2).size()==0)?false:true;
希望这会有所帮助