Home > Mobile >  Dart - split a string with elements contained in a list
Dart - split a string with elements contained in a list

Time:04-08

I'm quite inexperienced in coding and Dart. How do I start from a string and a list (with parts of the string inside) to split the string into the parts that are in the list.

I try to explain myself better:

this is the input I have:

void main() {
  String text = 'Hello I am Gabriele!';
  List ErrList = ['Hello', 'I'];
}

and this is the output I would like:

['Hello', ' ', 'I', ' am Gabriele']

I hope someone will help me. Thank you :)

CodePudding user response:

I don't know if you really need empty space in the list, but you can correct my example if you want to have spaces in the list.

void main() {
  String text = 'Hello I am Gabriele!';
  List<String> errList = ['Hello', 'I'];
  
  // `#` uses as separator.
  var a = text
      .split(' ')
      .map((e) => errList.contains(e) ? '$e#' : e)
      .join(' ')
      .split('#');

  print(a); // [Hello,  I,  am Gabriele!]
  print(a.join()); // Hello I am Gabriele!
}

According to your requirements:

void main() {
  String text = 'Hello I am Gabriele!';
  // Note: an empty space will be added after the objects except for the last one.
  // Order is important if you want the right results.
  List<String> errList = ['Hello', 'I'];

  var result = text
      .split(' ')
      .map((e) => errList.contains(e) ? e   '#' : e)
      .join(' ')
      .split('#')
      .expand((e) {
    if (errList.contains(e.trim()) && !e.contains(errList.last)) return [e, ' '];
    if (e.contains(errList.last)) return [e.trim()];
    return [e];
  }).toList();

  print(result); // [Hello,  , I,  am Gabriele!]
}
  • Related