我在 Rust 中有這段代碼:
for ch in string.chars() {
if ch == 't' {
// skip forward 5 places in the string
}
}
在 C 中,我相信你可以這樣做:
for (int i = 0; i < strlen(string); i) {
if (string[i] == 't') {
i = 4;
continue;
}
}
你將如何在 Rust 中實作這一點?謝謝。
uj5u.com熱心網友回復:
因為string.chars()給了我們一個迭代器,我們可以用它來創建我們自己的回圈,讓我們控制迭代器:
let string = "Hello World!";
let mut iter = string.chars();
while let Some(ch) = iter.next() {
if ch == 'e' {
println!("Skipping");
iter.nth(5);
continue;
}
println!("{}", ch);
}
將輸出:
H
Skipping
r
l
d
!
在線嘗試!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/417258.html
標籤:
