What Are String Methods in Rust?
String methods in Rust are predefined functions that operate on String or &str types to perform actions like modification, analysis, and transformation. These methods are part of the String and str standard library implementations.
Categories of String Methods
- Creating and Initializing Strings
- Analyzing Strings
- Modifying Strings
- Iterating Over Strings
- Transforming Strings
- Searching and Replacing
1. Creating and Initializing Strings
Rust provides several ways to create strings. Methods like new, from and to_string help initialize strings.
String: :new
Creates an empty string.
fn main() {
let s = String::new();
println!("Empty String: '{}'", s);
}
String: :from
Creates a String from a string literal.
fn main() {
let s = String::from("Hello, Rust!");
println!("{}", s);
}
to_string
Converts string literals or other types into a String.
fn main() {
let s = "Rust".to_string();
println!("{}", s);
}
2. Analyzing Strings
Rust provides methods to inspect and analyze strings, such as length, emptiness and containment checks.
len
Returns the length of the string in bytes.
fn main() {
let s = String: :from("Rust");
println!("Length: {}", s.len());
}
is_empty
Checks if the string is empty.
fn main() {
let s = String::new();
println!("Is empty: {}", s.is_empty());
}
contains
Checks if a substring exists within the string.
fn main() {
let s = String::from("Hello, Rust!");
println!("Contains 'Rust': {}", s.contains("Rust"));
}
3. Modifying Strings
Strings in Rust can be modified using methods like push, push_str, and truncate.
push
Adds a single character to the string.
fn main() {
let mut s = String::from("Rust");
s.push('!');
println!("{}", s);
}
push_str
Appends a string slice to the String.
fn main() {
let mut s = String::from("Hello");
s.push_str(", Rust!");
println!("{}", s);
}
truncate
Shortens the string to the specified length.
fn main() {
let mut s = String::from("Hello, Rust!");
s.truncate(5);
println!("{}", s);
}
clear
Removes all content from the string.
fn main() {
let mut s = String::from("Rust");
s.clear();
println!("Cleared String: '{}'", s);
}
4. Iterating Over Strings
Rust allows iteration over strings either by characters or bytes.
chars
Iterates over the characters of the string.
fn main() {
let s = String::from("Rust");
for c in s.chars() {
println!("{}", c);
}
}
bytes
Iterates over the bytes of the string.
fn main() {
let s = String::from("Rust");
for b in s.bytes() {
println!("{}", b);
}
}
5. Transforming Strings
You can transform strings using methods like to_uppercase, to_lowercase, and replace.
to_uppercase
Converts all characters to uppercase.
fn main() {
let s = String::from("rust");
println!("{}", s.to_uppercase());
}
to_lowercase
Converts all characters to lowercase.
fn main() {
let s = String::from("RUST");
println!("{}", s.to_lowercase());
}
replace
Replaces all occurrences of a substring with another substring.
fn main() {
let s = String::from("Hello, Rust!");
let replaced = s.replace("Rust", "World");
println!("{}", replaced);
}
6. Searching and Replacing
Rust provides methods to search and replace substrings efficiently.
find
Finds the position of a substring.
fn main() {
let s = String::from("Hello, Rust!");
if let Some(pos) = s.find("Rust") {
println!("Found 'Rust' at position: {}", pos);
}
}
split
Splits the string into parts based on a delimiter.
fn main() {
let s = String::from("Rust is fun");
for word in s.split(' ') {
println!("{}", word);
}
}
Other Useful Methods
- starts_with: Checks if the string starts with a specified prefix.
- ends_with: Checks if the string ends with a specified suffix.
- trim: Removes leading and trailing whitespace.
- repeat: Repeats the string a specified number of times.
Example: trim and repeat
fn main() {
let s = String::from(" Rust ");
println!("Trimmed: '{}'", s.trim());
let repeated = "Rust!".repeat(3);
println!("{}", repeated);
}