Strings in Rust: The Art of Text Handling
Strings in Rust are a bit like treasure chests—sometimes lightweight and simple, other times powerful and full of hidden surprises. Rust provides two main ways to handle text: String slices (&str) and owned Strings (String). Let’s break it down!
1. String Slices (&str)
A &str (string slice) is a reference to a sequence of characters stored in memory. These are fast, lightweight, and immutable by default.
Example:
fn main() {
let greeting: &str = "Hello, Rustacean!";
println!("{}", greeting);
}
Best used for fixed strings (like hardcoded text or function parameters).
2. Owned String (String)
The String type is growable and mutable, meaning you can modify it freely.
Example:
fn main() {
let mut message = String::from("Hello");
message.push_str(", Rust!");
println!("{}", message);
}
Best used when you need to modify or own the text.
3. Converting Between &str and String
Need to switch between &str and String? No problem!
fn main() {
let slice: &str = "Rust";
let owned: String = slice.to_string();
let back_to_slice: &str = &owned;
println!("{}", back_to_slice);
}
4. String Manipulation Tricks
Rust provides powerful methods to work with Strings.
a) Concatenation
Using + operator or .push_str():
fn main() {
let hello = String::from("Hello");
let world = " World!";
let result = hello + world;
println!("{}", result);
}
b) Repeating Strings
fn main() {
let repeated = "Na ".repeat(5) + "Batman!";
println!("{}", repeated);
}
c) Finding and Replacing
fn main() {
let sentence = String::from("I love Rust!");
let new_sentence = sentence.replace("love", "adore");
println!("{}", new_sentence);
}
d) Splitting Strings
fn main() {
let csv = "apple,banana,orange";
for fruit in csv.split(',') {
println!("{}", fruit);
}
}
e) Checking for Substrings
fn main() {
let text = "Rust is fast and safe!";
if text.contains("fast") {
println!("This text mentions speed!");
}
}
Wrapping Up
Rust’s string handling might seem strict at first, but it ensures memory safety and efficiency. Whether you're working with lightweight &str or powerful String, you now have all the tools to master text manipulation in Rust!
0 Comments:
Post a Comment