-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrings.rs
54 lines (46 loc) · 1.48 KB
/
strings.rs
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
pub fn string_examples() {
println!("String Examples");
println!();
let rand_string = "This is an example string";
// String length
println!("Length : {}", rand_string.len());
// Split a string in half at index
let (first, second) = rand_string.split_at(rand_string.len() / 2);
println!("First : '{}' Second : '{}'", first, second);
// We can easily split on whitespace
println!("Whitespace");
for s in rand_string.split_whitespace() {
print!("'{}', ", s)
}
println!();
let count = rand_string.chars().count();
let mut chars = rand_string.chars();
let mut indiv_char = chars.next();
println!("Chars");
loop {
// Pattern match like switch
match indiv_char {
// If show print
Some(x) => print!("'{}', ", x),
// If None break
None => break,
}
indiv_char = chars.next();
}
println!();
// Iterate over lines of string
let rand_string2 = "I am a random string\nThere are other strings like it\nThis string is the best";
let mut lines = rand_string2.lines();
let mut indiv_line = lines.next();
println!("Lines");
loop {
match indiv_line {
Some(x) => println!("Line: {}", x),
None => break,
}
indiv_line = lines.next();
}
println!();
// Find string in string
println!("Does string contain 'best'? : {}", rand_string2.contains("best"));
}