How to split a string by " " and then print first (or last) component

#1

I’m REALLY new at rust, and it is throwing me some curves.

What I want to do is just grab the first word off of a string, spliting at a space.

let chunks:Vec = vec!(address_string.split(" “).collect());
println!(”{}",chunks[0]);

It prints out the whole original string, with the spaces removed. I assume the “collect()” statement is to blame for this, but the split function won’t work without it. It would be just about as useful to have a vector with all the words in the string, but, I don’t know how to get there either.

My first attempt was this, and got the same results:

let chunks:String = address_string.split(" “).collect();
println!(”{}",chunks);

0 Likes

#2

If you want the words separated, then try the following:

let chunks: Vec<String> = address_string.split(" ").collect();
for i in chunks {
    println("{}", i);
}

This first splits them, and stores them into a Vec<String> and then iterates through them and prints them.
If you collect them into a string then you’ll end up with the chunks glued together into a single string, resulting in the same string, just without the spaces.

0 Likes

#3

What happened here is that you created a Vec<Vec<&str>> rather than a Vec<&str>, so chunks[0] returned the entire first vector. Do this instead:

let first_word = address_string
    .split_whitespace()
    .next()
    .unwrap_or("");

println!("{}", first_word);
2 Likes

#4

And for getting the last component, split iterators can also be stepped from the other end, using next_back() instead of next().

1 Like

#5

Thank you. And if I did want to save the parsed string into a vector, and step through addressing each one, how would that be accomplished?

0 Likes

#6

To get a vector, collect is the right method. But if, as you say, you just step through and do something with each element, you possibly don’t need a vector. Just use a for loop over the iterator (what is returned by split).

0 Likes

#7

Only allocate a vector if you need to. Iterators avoid the allocation.

let vector = iterator.collect::<Vec<_>();

Any type that implements FromIterator can be used with collect. That includes String, HashSet, BTreeSet, HashMap, BTreeMap, Result<T, E>, etc.

0 Likes