-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrings.rs
More file actions
43 lines (31 loc) · 1.02 KB
/
strings.rs
File metadata and controls
43 lines (31 loc) · 1.02 KB
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
// Primitive str = Immutable fixed-length string somewhere in memory
// String = Growable, heap-allocated data structure - Use when you need to modify or own string data
pub fn run() {
let mut hello = String::from("Hello ");
// Get length
println!("Length: {}", hello.len());
// Push char
hello.push('W');
// Push string
hello.push_str("orld!");
// Capacity in bytes
println!("Capacity: {}", hello.capacity());
// Check if empty
println!("Is Empty: {}", hello.is_empty());
// Contains
println!("Contains 'World' {}", hello.contains("World"));
// Replace
println!("Replace: {}", hello.replace("World", "There"));
// Loop through string by whitespace
for word in hello.split_whitespace() {
println!("{}", word);
}
// Create string with capacity
let mut s = String::with_capacity(10);
s.push('a');
s.push('b');
// Assertion testing
assert_eq!(2, s.len());
assert_eq!(10, s.capacity());
println!("{}", s);
}