summaryrefslogtreecommitdiff
path: root/rust/theBook/chapter-4-understanding-ownership/str.rs
blob: 09bab6791c14093f8a3a44409dfdeb293b22fe65 (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
27
28
29
30
31
32
33
34
35
36
37
38
fn first_word(s: &String) -> usize {
    let bytes = s.as_bytes();

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

    s.len()
}

fn second_word(s: &str) -> &str {
    let bytes = s.as_bytes();

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

    &s[0..s.len()]
}

fn main() {
    let mut s = String::from("hello world");

    let word = first_word(&s);

    println!("{word}");

    println!("{}",&s[0..5]);

    let word2 = second_word(&s[..]);

    println!("{}",&word2);
    s.clear();
}