capypad
0 day streak
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
rust
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 literal
let s1: String = String::from("Hello, world!");
// String slice - reference to part of a String
let slice: &str = &s1[0..5];
println!("Slice: {}", slice);
// String methods
let trimmed = " spaces around ".trim();
println!("Trimmed: '{}'", trimmed);
// Replacing text
let replaced = s1.replace("world", "Rust");
println!("Replaced: {}", replaced);
// Checking prefixes and suffixes
let phrase = String::from("Rust is awesome");
println!("Starts with 'Rust': {}", phrase.starts_with("Rust"));
println!("Ends with 'awesome': {}", phrase.ends_with("awesome"));
// Converting to uppercase
let 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