Hello,
I am a noob when it comes to programming in general, and Rust specifically.
I have arrived at chapter 4 by just figuring things out, but I noticed an oversight in one of the examples and wanted to fix it. First, about the code:
In the part about the slice type, there is an example to check the length of the first word in a string. I have added the fn main {...}
part to make it usable and made it work with user input like in the guessing game example:
use std::io;
fn main() {
let mut string = String::new();
io::stdin()
.read_line(&mut string)
.expect("failed to read line");
let length = first_word(&string);
println!("The length of the first word of your input is {} characters.", length);
}
fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
I noticed however, that there are two issues:
- If the first character in the string is a space, the length returned is 0, which is incorrect.
- If there is user input, there will be a newline character at the end, which will also falsify the length.
Both of these issues could be solved by using the trim() method on the string, but I get an error because it appears to change the type to &str
instead of &String
, at which point the first_word()
function is not happy anymore.
What would be (an) elegant solution(s) to solving this?
Thank you in advance!