gpt4 book ai didi

dart - 如何删除字符串中的前导 0

转载 作者:行者123 更新时间:2023-12-03 03:00:28 26 4
gpt4 key购买 nike

我以包含前导零的字符串格式获取 ID。我想保留此 String 格式但没有前导零。示例:

00 => 0
01 => 1
02 => 2
10 => 10
11 => 11

我目前的实现是String id = int.parse(originalId).toString()

是否有更好/更高效/Dart 模式的方式来实现这种转换?

最佳答案

您可以使用 RegExp,它可能更丑陋但比双重转换更快:

"01".replaceAll(new RegExp(r'^0+(?=.)'), '')

´^´ 匹配字符串的开头

0+ 匹配一个或多个 0 字符

(=?.) 匹配除换行符 (.) 之外的任何字符的组 (()),而不将其包含在结果 (=?),这确保不会匹配整个字符串,这样如果只有零,我们至少保留一个零。

示例:

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, '')}");
}

}

结果:

00 => 0
01 => 1
02 => 2
10 => 10
11 => 11

编辑:性能测试感谢您的评论

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}');

}

结果:

RegExp executed in 0:00:02.912000
Double conversion executed in 0:00:03.216000

与双重转换相比,您将执行的操作越多,效率就越高。然而 RegExp 在单次计算中可能会更慢,因为创建它需要成本,但我们说的是几微秒......我会说除非你有成千上万的操作,否则使用更方便的给你。

关于dart - 如何删除字符串中的前导 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61507170/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com