Strings in Rust
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.
What is a String
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.
Creating Strings
Strings can be created in Rust using String::from
or using a string literal:
let str1 = String::from("Hello, world!");
let str2 = "Hello, world!";
Example 1: Initializing Strings
- Create a string variable and initialize it with a value.
- Print the string variable using
println!
.
Rust Program
fn main() {
let str = String::from("Hello, world!");
println!("{}", str);
}
Output
Hello, world!
Example 2: Accessing Characters in a String
- Create a string variable and initialize it with a value.
- Access and print individual characters using the
chars
method.
Rust Program
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
}
Output
H e
Example 3: Modifying Strings
- Create a string variable and initialize it with a value.
- Strings in Rust are mutable, so you can modify them using various methods.
- Print the modified string.
Rust Program
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);
}
Output
Jello World!
Example 4: String Concatenation
- Create two string variables and initialize them with values.
- Concatenate the strings using the
+
operator or thepush_str
method. - Print the concatenated string.
Rust Program
fn main() {
let str1 = String::from("Hello");
let str2 = String::from(" World!");
let str3 = str1 + &str2; // Concatenating strings
println!("{}", str3);
}
Output
Hello World!
Example 5: Finding Substrings
- Create a string variable and initialize it with a value.
- Use the
contains
method to find a substring. - Print the existence of the substring.
Rust Program
fn main() {
let str = String::from("Hello, world!");
if str.contains("world") {
println!("Substring found");
} else {
println!("Substring not found");
}
}
Output
Substring found
Example 6: String Length
- Create a string variable and initialize it with a value.
- Use the
len
method to get the length of the string. - Print the length of the string.
Rust Program
fn main() {
let str = String::from("Hello, world!");
println!("Length of the string: {}", str.len());
}
Output
Length of the string: 13