Home > Net >  make a function which calculate the number of same nearby character in flutter like aabcddaabb =>
make a function which calculate the number of same nearby character in flutter like aabcddaabb =>

Time:06-24

can anybody help me to build the function mentioned above I am using dart in the flutter and want this function make a function which calculate the number of same nearby character in flutter like aabcddaabb => 2abc2d2a2b

CodePudding user response:

Same

void main() {
  var input = 'aabcddaabb';
  print(getret(input));
}

String getret(String input) {
  var ret = '';
  var cc = '';
  var co = 0;
  
  cut(){
    var c = input[0];
    input = input.substring(1);
    return c;
  }
  
  write(){
    if(co == 1) ret = '$ret$cc';
    if(co > 1) ret = '$ret$co$cc';
  }
  
  while(input.isNotEmpty){
    final c = cut();
    if(c != cc){
      write();
      cc = c;
      co = 1;
    }else{
      co   ;
    }
  }
  
  write();
  
  return ret; // 2abc2d2a2b
}

enter image description here

CodePudding user response:

There's probably a smarter and shorter way to do it, but here's a possible solution:

String string = 'aaabcddaabb';
String result = '';
String lastMatch = '';
int count = 0;
while (string.isNotEmpty) {
  if (string[0] != lastMatch) {
    result  = '${count > 1 ? count : ''}$lastMatch';
    lastMatch = string[0];
    count = 0;
  }
  count  ;
  string = string.substring(1);
}
result  = '${count > 1 ? count : ''}$lastMatch';
print(result); //3abc2d2a2b

I also came up with this smarter solution. Even though it's nice that it's a single expression it's maybe not very readable:

String string = 'aaabcddaabb';
String result = string.split('').fold<String>(
    '',
    (r, e) => r.isNotEmpty && e == r[r.length - 1]
        ? r.length > 1 &&
                int.tryParse(r.substring(r.length - 2, r.length - 1)) != null
            ? '${r.substring(0, r.length - 2)}${int.parse(r.substring(r.length - 2, r.length - 1))   1}$e'
            : '${r.substring(0, r.length - 1)}2$e'
        : '$r$e');
print(result); //3abc2d2a2b
  • Related