Je veux une fonction qui prend une chaîne comme argument et ajoute n'importe quel caractère entre les chaînes toutes les 3 lettres.
Par exemple:
func("11111111"){}
renverra: 11.111.111
4 Réponses :
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(',');
}
Si je comprends bien votre question
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;
}
UPD: (pour séparer les symboles de la fin, pas du début)
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;
}
la sortie de 1111111 doit être 1,111,111 et non 111,111,1 il doit commencer à placer "," de l'arrière.
Merci beaucoup
Essayez ceci:
Text(myFunction("111111111", ","))
Et utilisez-le par exemple, comme ceci:
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;
}
Désolé, mais j'ai oublié de mentionner qu'il doit commencer l'analyse à l'envers comme en dollar. Par exemple "11111" => "111,11" et non "11,111".
Les autres solutions fonctionnent pour votre problème déclaré, mais si vous cherchez à ajouter des virgules dans les nombres (comme dans votre exemple), vous voudrez plutôt ajouter les virgules de droite à gauche. c'est-à-dire: 12345678 que vous voudriez 12 345 678 et non 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();
}
J'ai mis à jour la réponse, veuillez vérifier