【发布时间】:2015-12-28 07:56:17
【问题描述】:
我正在用 Rust 重写一个 C++ 解析器以获取旧的 ASCII 数据格式。这种格式的实数值允许以任何 Fortran 识别的格式存储。不幸的是,Fortran 可以识别 Rust(或大多数其他语言)无法识别的某些格式。例如,值 101.01 可能表示为
- 101.01
- 1.0101E2
- 101.01e0
- 101.01D0
- 101.01d0
- 101.01+0
- 1010.1-1
前三个都是 Rust 原生识别的。其余四个构成挑战。在 C++ 中,我们使用以下例程来解析这些值:
double parse(const std::string& s){
char* p;
const double significand = strtod(&s[0], &p);
const long exponent = (*p == '\0') ?
0 : isalpha(*p) ?
strtol(p+1, nullptr) :
strtol(p, nullptr);
return significand * pow(10, exponent);
}
查看 Rust 文档后,标准库似乎没有像 strtod 和 strtol 那样提供部分字符串解析。出于性能原因,我想避免对字符串进行多次传递或使用正则表达式。
【问题讨论】:
标签: floating-point rust