1

I want a function which takes string as an argument and add any char between string after every 3 letters.

For example:

func("11111111"){}

will return:

11,111,111

1
  • I've updated answer, please check Commented May 22, 2019 at 12:42

4 Answers 4

2

If I understand your question correctly

import 'dart:math' as math;

String convertFun(String src, String divider) {
  String newStr = '';
  int step = 3;
  for (int i = 0; i < src.length; i += step) {
    newStr += src.substring(i, math.min(i + step, src.length));
    if (i + step < src.length) newStr += divider;
  }
  return newStr;
}

UPD: (for separating symbols from end, not from beginning)

String convertFun(String src, String divider) {
  String newStr = '';
  int step = 3;
  for (int i = src.length - 1; i >= 0; i -= step) {
    String subString ='';
    if (i > 3) {
      subString += divider;
    }
    subString += src.substring( i < step ? 0 : i - step, i);
    newStr = subString + newStr;
  }
  return newStr;
}
Sign up to request clarification or add additional context in comments.

1 Comment

the output of 1111111 must be 1,111,111 not 111,111,1 it must start placing "," from back.
1
String func(String str){    
    RegExp exp = RegExp(r".{1,3}");
    Iterable<Match> matches = exp.allMatches(str);

    List<dynamic> list = [];
    matches.forEach((m)=>list.add(m.group(0)));

    return list.join(',');
}

Comments

1

Try this:

  String myFunction(String str, String separator) {
    String tempString = "";
    for(int i = 0; i < str.length; i++) {
      if(i % 3 == 0 && i > 0) {
        tempString = tempString + separator;
      }
      tempString = tempString + str[i];
    }
    return tempString;
  }

And use it for example, like this:

Text(myFunction("111111111", ","))

1 Comment

Sorry, but i forgot to mention that it must start parsing from backwards like in dollar. For example "11111"=>"111,11"not"11,111" .
1

The other solutions work for your stated problem, but if you are looking to add commas in numbers (as in your example), you'll want to add the comma's from the right to the left instead. ie: 12345678 you would want 12,345,678 not 123,456,78

String convertFun(String src, String divider) {
    StringBuilder newStr = new StringBuilder();
    int step = 3;
    for (int i = src.length(); i > 0; i -= step) {
        newStr.insert(0, src.substring( i < step ? 0 : i - step, i));
        if (i > 3) {
            newStr.insert(0, divider);
        }
    }
    return newStr.toString();
}

Comments

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.