Michael
Michael

Reputation: 471

Dart/Flutter: Split string every nth character?

I have a single string made up of two digit numbers with leading zeros (ie '0102031522')

that I want to split into a list as integers without the leading zeros.

Output of this example should be [1,2,3,15,22].

I'm having trouble trying to get this converted as Dart is new to me, and i have no clue where to start. Any suggestions?

Upvotes: 6

Views: 5131

Answers (1)

Doc
Doc

Reputation: 11651

For any size split and making a list.

void main() {
  final splitSize = 2;
  RegExp exp = new RegExp(r"\d{"+"$splitSize"+"}");
  String str = "0102031522";
  Iterable<Match> matches = exp.allMatches(str);
  var list = matches.map((m) => int.tryParse(m.group(0)));
  print(list);
}

Tested on dartpad

Upvotes: 14

Related Questions