我正在尝试使用 Rust 读取文本文件,其中每行有两个由空格分隔的单词。我必须得到第一个单词的长度:
use std::fs;
fn main() {
let contents = fs::read_to_string("src/input.txt").expect("Wrong file name!");
for line in contents.split("\n") {
let tokens: Vec<&str> = line.split_whitespace().collect();
println!("{}", tokens[0].len());
}
}
input.txt 文件的内容是:
monk perl
我在 Windows 上运行并使用 cargo run。我收到以下错误(因为tokens[0].len()
):
4
thread 'main' panicked at 'index out of bounds: the len is 0 but the index is 0'
我不知道我的代码有什么问题。文件“input.txt”不为空。