gpt4 book ai didi

java - 根据原句子数组对句子数组进行排序

转载 作者:行者123 更新时间:2023-12-01 07:21:24 24 4
gpt4 key购买 nike

我有一个 SENTENCE1 数组,其中包含几个句子:

String[] SENTENCE1 = new String[]{
"This book is nice",
"I like it",
"I read them alot",
"My favourite book",
"I put it in a shelf"};

接下来,我还有一个从 SENTENCE1 数组中随机获得的句子数组,称为 SENTENCE2:

String[] SENTENCE2 = new String[]{
"I put it in a shelf" ,
"I like it",
"My favourite book"};

如何根据 SENTENCE1 中的出现顺序对 SENTENCE2 数组进行排序,以便 SENTENCE2 中的输出为:

I like it
My favourite book
I put it in a shelf

无论如何,我尝试这样做并循环它们,但它显示数组超出范围。

for (int g=0;g<SENTENCE2.length;g++){
for (int o=0;o<SENTENCE1.length;o++)
{
if (SENTENCE2[g].contains(SENTENCE1[o])){
System.out.println(SENTENCE2[g])
}
}
}

感谢您的帮助。

最佳答案

您的代码是正确的,一件事是如果要完成字符串的精确匹配,则不需要 contains 。使用等于

for(int i = 0; i < sent1.length; i++){
for(int j = 0; j < sent2.length; j++){
if(sent1[i].equals(sent2[j])){
System.out.println(sent2[j]);
}
}
}

在 java 中始终对局部变量使用驼峰式大小写

关于java - 根据原句子数组对句子数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36076531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com