u/Franklin00798

My try on The Book's 4.3 programming problem

The problem was:

Write a function that takes a string of words separated by spaces and returns the first word it finds in that string. If the function doesn’t find a space in the string, the whole string must be one word, so the entire string should be returned.

My try was:

fn main() {
    let string1 = String::from("testing");
    let string2 = String::from("This is a test");

    thingy(&string1);
    thingy(&string2)
}

fn thingy(s: &String) {
    for (i, c) in s.chars().enumerate() {
        let len = s.len() - 1;

        if c == ' ' {
            println!("{}", &s[0..i]);
            break;
        }

        if i == len {
            println!("{s}");
            break;
        }
    }
}

From what I've tried, it works well... I am now looking at The Book's solution and found it to be pretty confusing.

Would appreciate yall's opinion!

reddit.com
u/Franklin00798 — 4 days ago