0

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 :)

1 Answer 1

1

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!]
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thank you for your answer, can you please update your code for having spaces in the list?
Added example according to your requirements

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.