iaminpainpleasehelp1
iaminpainpleasehelp1

Reputation: 197

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) ? .....

Upvotes: 8

Views: 14150

Answers (3)

Solomon Tesfaye
Solomon Tesfaye

Reputation: 346

Dart has a filtering method to work with lists

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

The following will give you list of matching Items. You can do something with the result list

listS.where((element) => element.contains(s)).toList();

Or you can check the length if there was a match.

listS.where((element) => element.contains(s)).length;

Upvotes: 2

Kahou
Kahou

Reputation: 3488

Check whether any element of the iterable satisfies test

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

listS.any(test);

Upvotes: 16

Mostafa Ead
Mostafa Ead

Reputation: 41

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);
    } 
  });

Upvotes: 4

Related Questions