解析与验证
Coddy 面向 Ruby 开发者的 Dart 课程的第 24 课,共 48 课。
Ruby 的 String#to_i 接受数字前缀,遇到无效文本时可能返回 0。Integer 设置 exception: false 时,失败会返回 nil,但它接受的语法仍可能比严格的业务格式更宽松。Dart 的 int.tryParse 返回 null。请将语法验证和领域范围检查与转换分开。
int.tryParse 失败时返回 null,而 int.parse 会抛出异常。严格的业务语法可能需要在转换前进行语法检查,并在转换后单独进行范围检查。
完整的 Ruby 程序:
puts(Integer('nope', 10, exception: false) || 'invalid')
puts Integer('42', 10, exception: false)
完整的 Dart 程序:
void main(){print(int.tryParse('nope')??'invalid');print(int.tryParse('42'));}挑战
简单实现 bounded(String text):去除首尾空白,并解析一个十进制有符号整数。输入无效或数值超出 -50 到 50 的范围时,返回 null。输入中不含换行符。输出该值或 invalid。十进制输入只能包含可选符号和 ASCII 数字,不支持十六进制语法。
不要在可编辑文件中打印内容。提供的 exercise.dart 会解析输入并返回输出;锁定的驱动程序会独立测试公共 API,并在打印结果时附带一个换行符。
你的代码应写在 functions.dart、exercise.dart 中。main.dart 包含提供的输入/输出代码,不能编辑。
亲手试试
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'functions.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
check(bounded(' +7 ')==7 && bounded('7x')==null && bounded('-51')==null);
stdout.writeln(solve(input));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 Dart中的所有课
自己练习: Dart 在线编译器