string - 将文件按行然后按单词分割时,为什么会得到一个空向量?

标签 string file rust vec

我正在尝试使用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 运行。我收到以下错误(由于tokens[0].len()):
4
thread 'main' panicked at 'index out of bounds: the len is 0 but the index is 0'
我不知道我的代码有什么问题。文件“input.txt”不为空。

最佳答案

通过使用.split("\n"),您将在迭代器中获得两项。一个是您期望的行,另一个是换行符之后的空字符串。空字符串拆分成单词时为空。这意味着向量将为空,并且索引0处没有任何项目。
使用 str::lines 代替:

use std::fs;

fn main() {
    let contents = fs::read_to_string("src/input.txt").expect("AWrong file name!");

    for line in contents.lines() {
        let tokens: Vec<_> = line.split_whitespace().collect();

        println!("{}", tokens[0].len());
    }
}
也可以看看:
  • Is this the right way to read lines from file and split them into words in Rust?
  • 关于string - 将文件按行然后按单词分割时,为什么会得到一个空向量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64355360/

    相关文章:

    java正则表达式用单个字母替换word中的任何双字母

    file - 使用批处理文件递归查找和删除文件夹

    Python 打印错误消息 io.UnsupportedOperation : not readable

    android - 在 x86_64 上使用 x86_64 NDK 工具链链接失败

    macros - 如何在宏中允许可选的尾随逗号?

    c# - 如何在列表中查找字符串的索引

    C++ , 字符串数组

    javascript - 将逗号分隔的字符串分隔为新字符串

    c - 输入要写入文件的数据时出错

    rust - 将外部值传递给闭包...错误 : capture of moved value