我有一个包含几句话的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
无论如何,我试图这样做并循环遍历它们,但它显示Arrays不受限制。
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])
}
}
}
感谢您的帮助。
答案 0 :(得分:2)
您的代码是正确的,如果要完成String的完全匹配,有一点是您不需要contains
。使用equals
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中使用camel大小写用于局部变量
答案 1 :(得分:2)
试试这个。
inspect.getdoc(object)
inspect.getcomments(object)
inspect.getfile(object)
inspect.getmodule(object)
答案 2 :(得分:1)
TreeMap<Integer, String> map = new TreeMap<>();
for (int i=0;i<SENTENCE2.length;i++) {
for (int j = 0; j < SENTENCE1.length; j++) {
if (SENTENCE2[i].equals(SENTENCE1[j])) {
map.put(j, SENTENCE2[i]);
}
}
}
map.values().toArray(SENTENCE2);
for(String value: SENTENCE2){
System.out.println(value);
}
在TreeMap
中,值将自动按键排序。
答案 3 :(得分:1)
如果您乐意使用google guava之类的外部库。它可以很容易地完成如下:
public static void main(String[] args) {
String[] SENTENCE1 = new String[]{
"This book is nice",
"I like it",
"I read them alot",
"My favourite book",
"I put it in a shelf"};
String[] SENTENCE2 = new String[]{
"I put it in a shelf",
"I like it",
"My favourite book"};
Comparator<String> SENTENCE1_COMPARATOR = Ordering.explicit(Arrays.asList(SENTENCE1));
Arrays.sort(SENTENCE2, SENTENCE1_COMPARATOR);
System.out.println(Arrays.toString(SENTENCE2));
}
答案 4 :(得分:1)
@Test
public void test() {
String[] SENTENCE1 = new String[]{
"This book is nice",
"I like it",
"I read them alot",
"My favourite book",
"I put it in a shelf"};
String[] SENTENCE2 = new String[]{
"I put it in a shelf",
"I like it",
"My favourite book"};
System.out.println(SENTENCE1.length);
for(int i= 0 ;i<SENTENCE1.length;i++){
boolean flag = false;
for(int j = 0; j<SENTENCE2.length;j++){
if(SENTENCE2[j].equals(SENTENCE1[i])){
flag = true;
break;
}
}
if(!flag){
SENTENCE1[i]=null;
}
}
for(int k=0;k<SENTENCE1.length;k++){
if(SENTENCE1[k]!=null)
System.out.println(SENTENCE1[k]);
}
}