fn solve(s: &str) -> u32 {
s.split(char::is_alphabetic)
.map(|num| num.parse::<u32>().unwrap())
.max()
.unwrap()
}
fn main() {
assert_eq!(solve("gh12cdy695m1"), 695);
}
我不明白我为什么会出现这个错误:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: Empty }', src/main.rs:3:39
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
split
将在每个字母字符之间生成字符串,即使它们之间没有任何字符串:
fn main() {
let s = String::from("gh12cdy695m1");
for num in s.split(char::is_alphabetic) {
println!("{:?}", num);
}
}
""
""
"12"
""
""
"695"
"1"
在尝试解析这些空字符串之前,您应该过滤掉它们:
fn solve(s: &str) -> u32 {
s.split(char::is_alphabetic)
.filter(|s| !s.is_empty())
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
.map(|num| num.parse::<u32>().unwrap())
.max()
.unwrap()
}