简体   繁体   中英

Dart check if part of a string in a a list of strings contains an element

I have a string:

String s = "Hel";

I have a list of Strings.

List<String> listS = ["Hello", "Goodbye"];

The following will print true as "Hello" contains "Hel":

list[0].contains(s); 

The following will however print false:

list.contains(s);

What can I do to check if the list contains string S without giving an index? A loop is no option as I am using a ternary operator:

list.contains(s) ? .....

You can loop for every item an return true whenever an item contains the string as shown here :

String s = 'Hel';

  List<String> list = ['Egypt', 'Hello', 'Cairo'];

  bool existed = false;
  list.forEach((item) {
    if(item.contains(s)){
      existed = true;
      print(item);
    } 
  });

Check whether any element of the iterable satisfies test

test(String value) => value.contains(s);

listS.any(test);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM