rust / beginner
Snippet
String Slices and String Operations
Rust has two main string types: String (owned, growable) and &str (borrowed slice). String slices are references to a portion of a String or string literal. The standard library provides many useful methods for common operations like trimming, replacing, and case conversion. Always use &str when you don't need ownership.
snippet.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
fn main() {// Creating String from string literallet s1: String = String::from("Hello, world!");// String slice - reference to part of a Stringlet slice: &str = &s1[0..5];println!("Slice: {}", slice);// String methodslet trimmed = " spaces around ".trim();println!("Trimmed: '{}'", trimmed);// Replacing textlet replaced = s1.replace("world", "Rust");println!("Replaced: {}", replaced);// Checking prefixes and suffixeslet phrase = String::from("Rust is awesome");println!("Starts with 'Rust': {}", phrase.starts_with("Rust"));println!("Ends with 'awesome': {}", phrase.ends_with("awesome"));// Converting to uppercaselet upper = phrase.to_uppercase();println!("Uppercase: {}", upper);}
Breakdown
1
&s1[0..5]
Creates a string slice referencing characters 0 to 5
2
.trim()
Removes leading and trailing whitespace
3
.replace("world", "Rust")
Returns new String with all occurrences replaced
4
starts_with() / ends_with()
Boolean methods to check string boundaries