gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:44:38 26 4
gpt4 key购买 nike

我正在尝试使用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/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com