Rust string
Created By: chatGPT
Rust strings are a fundamental type used to store and manage Unicode text. In Rust, there are two main types of strings:
String
and &str
. The String
type is an owned, growable string, while &str
is a borrowed string slice that represents a view into a string.let owned_string = String::from("Hello, Rust!");
let str_slice: &str = &owned_string;
println!("{}", str_slice);
Creating a String can be done using the
String::from
method, or by using string literals directly. It is important to note that String
is mutable, which means you can change its contents after it's created.let mut my_string = String::from("Hello");
my_string.push_str(", World!");
println!("{}", my_string);
String Length can be determined using the
len
method, which returns the number of bytes in the string. Remember that the number of bytes may differ from the number of characters, especially in Unicode strings.let sample_string = String::from("नमस्ते");
println!("Length in bytes: {}", sample_string.len());
You can check whether a string contains a specific substring by using the
contains
method. This method returns a boolean indicating if the substring is present within the string.let text = String::from("Hello, Rust!");
if text.contains("Rust") {
println!("Found Rust!");
} else {
println!("Rust not found!");
}
To convert a
String
to a string slice (&str
), you can simply use a reference. This is useful when you need to pass a string to a function that expects a slice.let my_string = String::from("Hello, world!");
let string_slice: &str = &my_string;
process_string(string_slice);
fn process_string(s: &str) {
println!("Processing: {}", s);
}
To iterate over characters in a
String
, you can use the chars
method, which returns an iterator. This allows you to work with each character individually, regardless of its byte representation.let greeting = String::from("Hello");
for c in greeting.chars() {
println!("Character: {}", c);
}
If you want to split a string into parts based on a delimiter, you can use the
split
method. This can be particularly useful for parsing CSV or similar data formats.let data = String::from("apple,banana,cherry");
for fruit in data.split(',') {
println!("Fruit: {}", fruit);
}