Strings in Rust
Introduction to Strings
In Rust, strings are a sequence of characters and are used to store and manipulate text. Rust has two main types for strings: String
and &str
. The String
type is a growable, heap-allocated data structure, while &str
is a string slice, a reference to a string that is stored elsewhere.
Creating Strings
You can create a String
using the String::new()
method or by using string literals. Here are a couple of examples:
Creating an empty String:
Creating a String from a string literal:
String Slices
A string slice is a view into a string. It is represented by the type &str
. String slices are often used for function parameters when you do not need ownership of the string. Here's how you can create a string slice:
Creating a string slice:
String Concatenation
You can concatenate strings using the push_str()
method or the +
operator. Here are examples of both:
Using push_str()
:
hello.push_str("Rust!");
Using the +
operator:
let s2 = String::from("Rust!");
let s3 = s1 + &s2; // s1 is moved here
String Length
To find the length of a string, you can use the len()
method. This method returns the number of bytes in the string:
Finding the length of a string:
Looping Through Characters
You can loop through the characters of a string using a for
loop. Here's an example:
Looping through characters:
for c in my_string.chars() {
println!("{}", c);
}
Common String Methods
Rust's String type provides many useful methods. Here are a few commonly used methods:
to_uppercase()
: Converts all characters to uppercase.to_lowercase()
: Converts all characters to lowercase.contains()
: Checks if the string contains a specified substring.trim()
: Removes whitespace from both ends of the string.
Using some common string methods:
let upper = my_string.to_uppercase();
let trimmed = my_string.trim();
let contains = my_string.contains("Rust"); // returns true
Conclusion
Strings in Rust are powerful and flexible, allowing for efficient text manipulation. By understanding the differences between String
and &str
, as well as various string methods, you can effectively manage text in your Rust programs. Experiment with these features to become proficient in handling strings in Rust!