Search code examples
flutterdart

split the string into equal parts flutter


There is a string with random numbers and letters. I need to divide this string into 5 parts. And get List. How to do it? Thanks.

String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';

Should work:

List<String> list = [
  '05b37ffe',
  '4973959c',
  '4d4f2d5c',
  'a0c14357',
  '49f8cc66',
];

Solution

  • I know there'a already a working answer but I had already started this so here's a different solution.

    String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
     List<String> list = [];
    
     final divisionIndex = str.length ~/ 5;
    
     for (int i = 0; i < str.length; i++) {
        if (i % divisionIndex == 0) {
        final tempString = str.substring(i, i + divisionIndex);
           list.add(tempString);
         }
       }
      log(list.toString()); // [05b37ffe, 4973959c, 4d4f2d5c, a0c14357, 49f8cc66]