I'm trying to read a text file with Rust where each line has two words separated by a whitespace. I have to get the length of the first word:
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());
}
}
The content of the input.txt file is:
monk perl
I'm running on Windows and using cargo run. I get the following error (because of tokens[0].len()
):
4
thread 'main' panicked at 'index out of bounds: the len is 0 but the index is 0'
I don't know what's wrong with my code. The file "input.txt" is not empty.
By using .split("\n")
, you are getting two items in the iterator. One is the line that you expect, the other is the empty string after the newline. The empty string, when split into words, is empty. This means the vector will be empty and there is not an item at index 0.
Use str::lines
instead:
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());
}
}
See also: