Search code examples
dartsplit

Flutter/Dart: Split string by first occurrence


Is there a way to split a string by some symbol but only at first occurrence?

Example: date: '2019:04:01' should be split into date and '2019:04:01'
It could also look like this date:'2019:04:01' or this date : '2019:04:01' and should still be split into date and '2019:04:01'

string.split(':');

I tried using the split() method. But it doesn't have a limit attribute or something like that.


Solution

  • You were never going to be able to do all of that, including trimming whitespace, with the split command. You will have to do it yourself. Here's one way:

    String s = "date   :   '2019:04:01'";
    int idx = s.indexOf(":");
    List parts = [s.substring(0,idx).trim(), s.substring(idx+1).trim()];