I get Ids in a String format that contain leading zeroes. I would like to keep this String format but without the leading zeroes. Example:
00 => 0
01 => 1
02 => 2
10 => 10
11 => 11
My current implementation is String id = int.parse(originalId).toString()
Is there a better / efficient / Dart pattern way to achieve this conversion ?
You could use RegExp which may be uglier but faster than double conversion :
"01".replaceAll(new RegExp(r'^0+(?=.)'), '')
´^´ matches the begining of the string
0+ matches one or more 0 character
(=?.) matches a group (()) of any characters except line breaks (.) without including it in the result (=?), this ensures that not the entire string will be matched so that we keep at least one zero if there are only zeroes.
Example :
void main() {
final List nums = ["00", "01", "02", "10", "11"];
final RegExp regexp = new RegExp(r'^0+(?=.)');
for (String s in nums) {
print("$s => ${s.replaceAll(regexp, '')}");
}
}
Result :
00 => 0
01 => 1
02 => 2
10 => 10
11 => 11
EDIT : Performance test thanks to your comment
void main() {
Stopwatch stopwatch = Stopwatch()..start();
final RegExp reg = RegExp(r'^0+(?=.)');
for (int i = 0; i < 20000000; i++) {
'05'.replaceAll(reg, '');
}
print('RegExp executed in ${stopwatch.elapsed}');
stopwatch = Stopwatch()..start();
for (int i = 0; i < 20000000; i++) {
int.parse('05').toString();
}
print('Double conversion executed in ${stopwatch.elapsed}');
}
Result :
RegExp executed in 0:00:02.912000
Double conversion executed in 0:00:03.216000
The more operations you will do the more it will be efficient compared to double conversion. However RegExp may be slower in a single computation because creating it has a cost, but we speak about a few microseconds... I would say that unless you have tens of thousands of operations just use the more convenient to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With