derChris
derChris

Reputation: 890

Filter strings containing a word in Flutter

I want to filter a list and remove Strings not containing words starting with a particular string.

Fe.: searching for words starting with "some"

"That is a list of some animals" - should be in the result

"That is a list of something like animals" - should be in the result

"That is a list of handsome animals" - should not be in the result

Upvotes: 0

Views: 1264

Answers (2)

Rizwan
Rizwan

Reputation: 441

The question is already been answered in the simplest form of code. But I am doing it in a layman's way.

final list = [
  'That is a list of some animals',
  'That is a list of something like animals',
  'That is a list of handsome animals',
];
  
for(var i = 0 ; i < list.length ; i++){
  var sentence = list[i].split(' ');
  bool found = false;

  for(var j = 0 ; j < sentence.length ; j++){    
    if (sentence[j].startsWith('some')){
      found = true;
    }
  }

  if(!found){
    list.removeAt(i);
    found = false;
  }
}
  1. Stored three sentences in the list.
  2. Used a loop to get each sentence.
  3. Split the sentence on the basis of space, to get each word.
  4. Used an array to check each word of the sentence, whether it is starting from some
  5. If any word of the sentence is starting from some, then I removed that sentence from the list

Upvotes: 0

Ramin
Ramin

Reputation: 935

Might not be the most performant, but unless you're doing this on millions of items, there shouldn't be any problem:

final l = [
  'That is a list of some animals',
  'That is a list of something like animals',
  'That is a list of handsome animals',
];

l.retainWhere((str) => str.split(' ').any((word) => word.startsWith('some')));

Upvotes: 2

Related Questions