How to get a word out of a String?

Hey, gang. Sorry if this is a newbie question, but I have a variable, msg: String whose value is "Hello World."
How would I get the words "Hello" and "word" into their own variables? Is this possible?

you split them using space as speparator, which returns an iterator. then you can iterate through the words.

let mut words = msg.split(' ');
let first =;
let second =;
1 Like

btw, to get all the words, you can collect the iterator into a Vec, which allows you to use the slice pattern to bind variables to single item:

let words: Vec<&str> = msg.split(' ').collect();
let [first, second] = words.as_slice()  else { unreachable!() };

See also str::split_whitespace for an existing method for splitting "words" on any amount of any kind of whitespace.


I love code golf questions. I was hoping to create a one-liner for this, but let-else was the best I could come up with, too:

fn main() {
    let &[hello, world] = "hello world".split(' ').collect::<Vec<_>>().as_slice() else {
        panic!("expected exactly two words in the string");
    assert_eq!(hello, "hello");
    assert_eq!(world, "world");


1 Like

Thank you! This works perfect. Is it possible to use this method to get specific words from strings with multiple words? For example, in the string "there is beauty and there's magic in the air," how would i get the only words "beauty" and "magic"

Note that for more complex scenarios, i.e. also including all sorts of punctuation that should be ignored, the unicode-segmentation crate provides the unicode_words method on strings that handles all of these cases.

1 Like

It's not really clear what you are asking for. If you already knew what two words you want, then you would just create those two words as literals, no?

let words = ["beauty", "magic"];

Obviously, this is useless/likely not what you are asking for. Are you trying to get words at specific indices? Are you trying to get the indices of specific words? Are you trying to fully parse a natural language sentence?

1 Like

Yeah i realize that the way I phrased the question wasn't great. What I meant to ask was How do i search a string for a specific word/words ?

That's str::find if you need the byte indices of the words.

For finding occurrences of multiple words at once, you can use Aho-Corasick.


Awesome !!!! thank you so much

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.