如何在for循环中更改变量的值?

时间:2020-03-30 17:43:33

标签: rust lifetime

我正在学习Rust,并且编写了一个小程序,该程序应该返回句子中的第n个单词。

我的问题是,我必须一直跟踪是否已经达到指定的n(随着递增),它不会在下一次迭代中保持递增,而是从1开始。这似乎是一个我还不了解在Rust中的寿命如何工作的问题。如果有人能让我知道我是否在这里遗漏了什么,那将会很有帮助。

这是我的main.rs文件:

fn main() {
    let first_string = String::from("There is a sentence here.");

    let answer_01 = return_nth_word(&first_string, 3);
    println!("Word 3 in {}: {}", first_string, answer_01);

}

fn return_nth_word(s: &str, idx: usize) -> &str {
    let bytes = s.trim().as_bytes();

    let mut count: usize = 1;
    let mut begin: usize = 0;

    for (i, &item) in bytes.iter().enumerate() {
        if count <= idx {
            if item == b' ' {
                println!{"Index at space: {}", i};
                if count == idx {
                    let mut end = i + 1;
                    return &s[begin..end];
                }
                let mut begin = idx + 1;
                println!("COUNT BEFORE: {}", count);  //printing here to demonstrate failed iteration
                let mut count = count + 1;
                println!("COUNT AFTER: {}", count);   //printing here to demonstrate failed iteration

                // The problem is the variable in the for
                // loop does not change the variable
                // outside of it. So I need to find another
                // way of iterating over that.

            }
        }
    }
    s
}

这是输出:

Index at space: 5
COUNT BEFORE: 1
COUNT AFTER: 2         
Index at space: 8
COUNT BEFORE: 1
COUNT AFTER: 2 <---- count continually increments from 1 to 2 on each iteration instead of counting up
Index at space: 10
COUNT BEFORE: 1
COUNT AFTER: 2
Index at space: 19
COUNT BEFORE: 1
COUNT AFTER: 2
Word 3 in There is a sentence here.: There is a sentence here.

0 个答案:

没有答案