Mustafa k
Mustafa k

Reputation: 13

How to split a String in Rust that I take as an input with read!()

I want to split a String that I give as an input according to white spaces in it. I have used the split_whitespaces() function but when I use this function on a custom input it just gives me the first String slice.

let s:String = read!();
let mut i:usize = 0;
for token in s.split_whitespace() {
    println!("token {} {}", i, token);
    i+=1;
}

What am I missing?

Upvotes: 1

Views: 1888

Answers (2)

Simson
Simson

Reputation: 3559

You are missing test cases which could locate the source of the problem. Split the code into a function and replace the read!()-macro with a test case, which you could put in main for now, where you provide different strings to the function and observe the output.

fn strspilit(s:String){
    let mut i:usize = 0;
    for token in s.split_whitespace() {
        println!("token {} {}", i, token);
        i+=1;
    }
}


fn main() {
    println!("Hello, world!");
    strspilit("Hello Huge World".to_string());

}

Then you will see your code is working as it should but as notices in other answers the read!() macro is only returning the string until the first white space so you should probably use another way of reading your input.

Upvotes: 0

rodrigo
rodrigo

Reputation: 98328

As far as I know, read! is not a standard macro. A quick search reveals that is probably is from the text_io crate (if you are using external crates you should tell so in the question).

From the docs in that crate:

The read!() macro will always read until the next ascii whitespace character (\n, \r, \t or space).

So what you are seeing is by design.

If you want to read a whole line from stdin you may try the standard function std::Stdin::read_line.

Upvotes: 1

Related Questions