在字符串中查找与列表中的项目匹配的序列。

huangapple go评论86阅读模式
英文:

Find the sequence in the String matches the items in the List

问题

以下是代码的翻译部分:

假设我有一个列表然后我将名字添加到列表中

List<String> listOfName = new ArrayList();
listOfName.add("abc");
listOfName.add("pqr");
listOfName.add("xyz");

并且我有一个字符串 `String names = "abc\r\npqr\r\nxyz";`

我想要验证字符串是否按照列表中元素的顺序组成

例如abc 应该首先出现然后是 pqr然后是 xyz

我试图做的是

int flag = 1;
for(int i=0; i<listOfName.size()-1;i++){
    if(names.replace("\r\n","").split(listOfName.get(i))[1].indexOf(listOfName.get(i+1))!=0){
        flag = 0;
        break;
    }
}
if(flag==1){
    System.out.println("True");
} else {
    System.out.println("False");
}

是否有更好的解决方案来实现相同的功能?我怀疑这种方法可能在某些情况下失败。

英文:

Suppose I have a list and then I add names to the list

List&lt;String&gt; listOfName = new ArrayList();
listOfName.add(&quot;abc&quot;);
listOfName.add(&quot;pqr&quot;);
listOfName.add(&quot;xyz&quot;);

And I have a String String names = &quot;abc\r\npqr\r\nxyz&quot;;

I want to verify that the string is comprised in the same order as the elements in the list are.

eg: abc should come first then pqr and then xyz

What I am trying to do:

int flag = 1;
for(int i=0; i&lt;listOfName.size()-1;i++){
    if(names.replace(&quot;\r\n&quot;,&quot;&quot;).split(listOfName.get(i))[1].indexOf(listOfName.get(i+1))!=0){
        flag = 0;
        break;
    }
}
if(flag==1){
    System.out.println(&quot;True&quot;);
} else {
    System.out.println(&quot;False&quot;);
}

Is there any better solution for doing the same as I doubt that it might fail in some scenarios

答案1

得分: 2

你可以使用 String.join 来实现这个目的,通过从项目列表创建一个String,并将 (Windows-) 换行符 (\r\n) 作为分隔符。然后检查它是否等于 String names,如下所示:

public static void main(String[] args) {
    List&lt;String&gt; listOfName = new ArrayList&lt;&gt;();
    listOfName.add(&quot;abc&quot;);
    listOfName.add(&quot;pqr&quot;);
    listOfName.add(&quot;xyz&quot;);
    
    String names = &quot;abc\r\npqr\r\nxyz&quot;;
    
    // 从列表的项目创建一个以换行符分隔的字符串
    String listItems = String.join(&quot;\r\n&quot;, listOfName);

    /*
     * 并将其与可能包含这些项目的字符串进行比较
     * 以它们在列表中出现的顺序
     */
    if (listItems.equals(names)) {
        System.out.println(listItems + &quot;\r\n== 相等 ==\r\n&quot;+ names);
    } else {
        System.err.println(listItems + &quot;\r\n!= 不等于 !=\r\n&quot; + names);
    }
}

这将输出:

abc
pqr
xyz
== 相等 ==
abc
pqr
xyz
英文:

You can utilize String.join for this purpose by creating a String from the list of items and put a (Windows-) linebreak (\r\n) as delimiter. Then check if it is equal to the String names, like this:

public static void main(String[] args) {
	List&lt;String&gt; listOfName = new ArrayList&lt;&gt;();
	listOfName.add(&quot;abc&quot;);
	listOfName.add(&quot;pqr&quot;);
	listOfName.add(&quot;xyz&quot;);
	
	String names = &quot;abc\r\npqr\r\nxyz&quot;;
	
	//  create a linebreak-separated String from the items of the list
	String listItems = String.join(&quot;\r\n&quot;, listOfName);

	/*
	 *  and compare it to the String that might contain those items
	 *  in the order they appear in the list 
	 */
	if (listItems.equals(names)) {
		System.out.println(listItems + &quot;\r\n== equals ==\r\n&quot;+ names);
	} else {
		System.err.println(listItems + &quot;\r\n!= is not equal to !=\r\n&quot; + names);
	}
}

This outputs

abc
pqr
xyz
== equals ==
abc
pqr
xyz

答案2

得分: 2

以下是翻译好的代码部分:

public class CompareList {

    public static void main(String[] args) {
    	List<String> listOfNames = new ArrayList<String>();
    	listOfNames.add("abc");
    	listOfNames.add("pqr");
    	listOfNames.add("xyz");
    	
    	String names = "abc\r\npqr\r\nxyz"; // define string
    	boolean match = checkList(listOfNames, names, "\r\n"); //check match
    	System.out.println(match); //print match
    }
    
    private static boolean checkList(
    		List<String> list,
    		String content,
    		String delimiter) {
    	
    	return Arrays.asList(
    			content.split(Pattern.quote(delimiter))).equals(list);
    }
    
}

这将打印出 true

在这里,你有一个名为 checkList()(或者你喜欢的任何名称)的方法,它使用给定的分隔符(在你的情况下是 \r\n)拆分字符串,将结果数组转换为 List,然后只需在输入的 List 上调用 equals() 来将其与输入的 List 进行比较,因为 Listequals() 实现是“如果且仅如果指定的对象也是一个列表,两个列表具有相同的大小,并且两个列表中对应的元素对都相等时返回 true”。

英文:

Well, there is certainly a more "abstract" and semantically pretty way to do this:

public class CompareList {

    public static void main(String[] args) {
    	List&lt;String&gt; listOfNames = new ArrayList&lt;String&gt;();
    	listOfNames.add(&quot;abc&quot;);
    	listOfNames.add(&quot;pqr&quot;);
    	listOfNames.add(&quot;xyz&quot;);
    	
    	String names = &quot;abc\r\npqr\r\nxyz&quot;; // define string
    	boolean match = checkList(listOfNames, names, &quot;\r\n&quot;); //check match
    	System.out.println(match); //print match
    }
    
    private static boolean checkList(
    		List&lt;String&gt; list,
    		String content,
    		String delimiter) {
    	
    	return Arrays.asList(
    			content.split(Pattern.quote(delimiter))).equals(list);
    }
    
}

This will print true.

Here you have method checkList() (or whatever name you like) that splits the string using the given delimiter (\r\n in your case), turns the resulting array into a List and just calls equals() on it to compare it with the input List, as the equals() implementation of List (i quote) "Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal.".

答案3

得分: 2

使用Java 8

String names = listOfName.stream().collect(Collectors.joining("\r\n"));

Collectors.joining 的文档 -

返回一个 Collector,它按出现顺序将输入元素连接在一起,以指定的分隔符分隔。

英文:

Using Java 8

String names = listOfName.stream().collect(Collectors.joining(&quot;\r\n&quot;));

Documentation of Collectors.joining -

> Returns a Collector that concatenates the input elements, separated by
> the specified delimiter, in encounter order.

答案4

得分: 2

尝试这个。

List<String> listOfName = new ArrayList<>();
listOfName.add("abc");
listOfName.add("pqr");
listOfName.add("xyz");
String names = "abc\r\npqr\r\nxyz";
System.out.println(String.join("\r\n", listOfName).equals(names));

输出

true
英文:

Try this.

List&lt;String&gt; listOfName = new ArrayList&lt;&gt;();
listOfName.add(&quot;abc&quot;);
listOfName.add(&quot;pqr&quot;);
listOfName.add(&quot;xyz&quot;);
String names = &quot;abc\r\npqr\r\nxyz&quot;;
System.out.println(String.join(&quot;\r\n&quot;, listOfName).equals(names));

output

true

答案5

得分: 1

你可以将列表转换成数组,然后使用 Arrays.equals 来将其与在 \r\n 上拆分字符串后获得的数组进行比较。

演示代码:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> listOfName = new ArrayList<>();
        listOfName.add("abc");
        listOfName.add("pqr");
        listOfName.add("xyz");

        String names = "abc\r\npqr\r\nxyz";
        String[] namesArr = names.split("\r\n");

        System.out.println(Arrays.equals(namesArr, listOfName.toArray()));
    }
}

输出:

true
英文:

You can convert the list into an array and then use Arrays.equals to compare it with the array obtained after splitting the string on \r\n.

Demo:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
	public static void main(String[] args) {
		List&lt;String&gt; listOfName = new ArrayList&lt;&gt;();
		listOfName.add(&quot;abc&quot;);
		listOfName.add(&quot;pqr&quot;);
		listOfName.add(&quot;xyz&quot;);

		String names = &quot;abc\r\npqr\r\nxyz&quot;;
		String[] namesArr = names.split(&quot;\r\n&quot;);

		System.out.println(Arrays.equals(namesArr, listOfName.toArray()));
	}
}

Output:

true

答案6

得分: 1

以下是翻译好的代码部分:

import java.util.List;
import java.util.ArrayList;

class Main {
  public static void main(String[] args) {
    List<String> listOfName = new ArrayList();
    listOfName.add("abc");
    listOfName.add("pqr");
    listOfName.add("xyz");

    String names = "abc\r\npqr\r\nxyz";
    String[] splitted_names = names.split("\r\n");

    boolean noNameFound = true;
    for (String name : splitted_names) {
      if (listOfName.contains(name)) {
        System.out.println("Found name " + name + " in listOfName! ");
        noNameFound = false;
      } 
    }
    if (noNameFound) {
      System.out.println("No name found that matched");
    }
  }
}
英文:

A working example here:

import java.util.List;
import java.util.ArrayList;


class Main {
  public static void main(String[] args) {
    List&lt;String&gt; listOfName = new ArrayList();
    listOfName.add(&quot;abc&quot;);
    listOfName.add(&quot;pqr&quot;);
    listOfName.add(&quot;xyz&quot;);

    String names = &quot;abc\r\npqr\r\nxyz&quot;;
    String[] splitted_names = names.split(&quot;\r\n&quot;);

    boolean noNameFound = true;
    for (String name : splitted_names) {
      if (listOfName.contains(name)) {
        System.out.println(&quot;Found name &quot; + name + &quot; in listOfName! &quot;);
        noNameFound = false;
      } 
    }
    if (noNameFound) {
          System.out.println(&quot;No name found that matched&quot;);
    }

  }
}

huangapple
  • 本文由 发表于 2020年8月10日 18:05:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63338105.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定