summaryrefslogtreecommitdiff
path: root/rust/chap4/slice_me.rs
blob: da201a144b371c4c9c08f379eb8d30adc90ef0c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

/* Return the index of the first space or s.len()*/
fn get_word_index(s: &str) -> usize {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return i;
        }
    }

    return s.len();
}

fn first_word(s: &str) -> &str {
    let idx = get_word_index(s);

    return &s[..idx];
}

fn main() {
    let s = String::from("corno manso ronaldo curintiano");
    let slice = first_word(&s);

    println!("{slice}");
}