我在变量String语句中有一个输入句子,想要与java中的一组String [] sentence2进行比较,如下所示
String sentence = "I am fine today";
String[] sentence2= {"how are %s to day", I am %s today","thank %s for you answer"}
此问题的输出结果为真实条件(匹配)并检索单词"罚款"。 如果输入改变如下:String sen =我今天很开心,输出结果为真实条件(匹配)并检索单词"罚款"
我有一个函数并使用split将句子分成单词并与数组单词
进行比较 if (similarity(sentence,sentence2)>2) {
String a = getkata(sentence, sentence2);
..
}
public static int similarity(String a, String b) {
int count = 0;
String[] words = a.split(" ");
// String[] words2=b.split(" ");
for (int i=0; i < words.length; i++){
if(b.contains(words[i])) {
System.out.println(i);
count=count+1;
}
}
return count;
}
public static String getkata(String a, String b){
String hasil="";
String[] kata = a.split(" ");
String[] cari = b.split(" ");
for (int i=0; i< kata.length; i++){
if(cari[i].contains("%s")){
hasil = kata[i];
}
}
return hasil;
}
这段代码工作,但我希望代码直接比较两个句子而不分成单词
答案 0 :(得分:1)
如果您可以将%s
替换为(.*?)
,那么您可以解决90%的问题,例如可以使用匹配进行检查:
public static void main(String[] args) {
String sen = "I am fine today";
String[] sen2 = {"how are (.*?) to day", "I am (.*?) today", "thank (.*?) for your answer"};
for (String s : sen2) {
if (sen.matches(s)) {
System.out.print("Matche : ");
System.out.println(sen);
}else{
System.out.println("Not Matche");
}
}
}
这将告诉你:
Not Matche
Matche : I am fine today
Not Matche
修改强>
我想要一个布尔值为真的答案并检索%s字
在这种情况下,您可以使用Pattern和Matches作为例子:
public static void main(String[] args) {
String sen = "I am fine today";
String[] sen2 = {"how are (.*?) to day", "I am (.*?) today", "thank (.*?) for your answer"};
Pattern pattern;
Matcher matcher;
for (String s : sen2) {
pattern = Pattern.compile(s);
matcher = pattern.matcher(sen);
if (matcher.find()) {
System.out.println("Yes found : " + matcher.group(1));
}
}
}
<强>输出强>
Yes found : fine
答案 1 :(得分:0)
这应该有效:
for (String s: sen2) {
Pattern pat = Pattern.compile(s.replace("%s", "(.*)"));
Matcher matcher = pat.matcher(sen);
if (matcher.matches()) {
System.out.println(matcher.group(1));
}
}