50.2.1Loop exercise¶
let mut n = 0;
loop {
n += if n % 2 == 0 { 3 } else { 1 };
println!("{n}");
if n > 30 {
break;
}
}3
4
7
8
11
12
15
16
19
20
23
24
27
28
31
()50.2.2Checker¶
Here are the two for loops needed to draw the grid:
for i in 0..20 {
for j in 0..i {
print!("{}", if (i+j)%2==0 {'X'} else {' '});
}
println!();
}
X
X
X X
X X
X X X
X X X
X X X X
X X X X
X X X X X
X X X X X
X X X X X X
X X X X X X
X X X X X X X
X X X X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X X
X X X X X X X X X
()50.2.3Multiple search in a string¶
We define the letters and the string:
let s = "abcdefghijklmnop";
let letters = ['c', 'a', 't', 'z', 'h'];We loop on each letter to search for, and test the result of find()
using if let Some(...):
for letter in letters {
if let Some(index) = s.find(letter) {
println!("Found {letter} at index {index}.");
}
}Found c at index 2.
Found a at index 0.
Found h at index 7.
()50.2.4Iterating over results¶
We define the string variable:
let s = "abc\nde\nfghi\njklm\nnop\n";We store the iterator returned by lines():
let mut lines = s.lines();Couldn't automatically determine type of variable `lines`.
Please give it an explicit type.We use the while let construct to iterate over all results until the
end (None value):
while let Some(line) = lines.next() {
println!("{line}");
}