In this tutorial, we will learn about strings in Rust. We will cover the basics of string manipulation, including creating, accessing, modifying, and performing operations on strings.
A string in Rust is a sequence of characters. Rust has two main types of strings: String
and &str
. The String
type is a growable, mutable, owned, UTF-8 encoded string, while &str
is an immutable reference to a string slice.
Strings can be created in Rust using String::from
or using a string literal:
let str1 = String::from("Hello, world!");
let str2 = "Hello, world!";
println!
.fn main() {
let str = String::from("Hello, world!");
println!("{}", str);
}
Hello, world!
chars
method.fn main() {
let str = String::from("Hello");
println!("{}", str.chars().nth(0).unwrap()); // Accessing using chars and nth method
println!("{}", str.chars().nth(1).unwrap()); // using chars and nth method
}
H e
fn main() {
let mut str = String::from("Hello");
str.replace_range(0..1, "J"); // Modifying a character
str.push_str(" World!"); // Appending new characters
println!("{}", str);
}
Jello World!
+
operator or the push_str
method.fn main() {
let str1 = String::from("Hello");
let str2 = String::from(" World!");
let str3 = str1 + &str2; // Concatenating strings
println!("{}", str3);
}
Hello World!
contains
method to find a substring.fn main() {
let str = String::from("Hello, world!");
if str.contains("world") {
println!("Substring found");
} else {
println!("Substring not found");
}
}
Substring found
len
method to get the length of the string.fn main() {
let str = String::from("Hello, world!");
println!("Length of the string: {}", str.len());
}
Length of the string: 13