What is String
- Rust's core language has only one string type, which is the string slice
str, usually seen as a borrowed&str. - The
Stringtype is provided by the standard library rather than encoded directly into the core language. It is a growable, mutable, UTF-8 encoded type. - Both
strandStringare UTF-8 encoded. If you need a non-UTF-8 string, you can useOsString.
Creating a New String
Stringis actually implemented by wrapping a vector of bytes.- Create a
Stringusing thenewmethod:let mut s = String::new(). - Create a
Stringusing theto_stringmethod:let data = "initial contents"; let s = data.to_string(); let s = "initial contents".to_string(); - Create a string using
String::from:let s = String::from("initial contents"). - Create an empty string with a specified capacity:
let mut s = String::with_capacity(10);. Memory reallocation won't be triggered as long as the string length is less than 10. - Check string length with
lenand capacity withcapacity. - Create a string from a UTF-8 vector:
let s_from_vec = String::from_utf8(vec![0xe4, 0xbd, 0xa0, 0xe5, 0xa5, 0xbd]);. - If the vector might contain invalid UTF-8, use
from_utf8_lossywhich replaces invalid characters with a placeholder:let invalid_utf8 = vec![0xff, 0xff, 0xff]; let s_from_invalid_utf8 = String::from_utf8_lossy(&invalid_utf8);
Updating a String
Rust does not allow indexing into a string to access individual characters.
Appending with push_str and push
let mut s = String::from("foo");
s.push_str("bar");
// s is now "foobar"
The push_str method does not take ownership of the string.
let mut s = String::from("lo");
s.push('l');
// s is now "lol"
Concatenating with + Operator or format! Macro
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used
let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");
let s = format!("{s1}-{s2}-{s3}");
Increasing String Capacity
let mut s_origin = String::with_capacity(10);
s_origin.push('1');
s_origin.reserve(10);
println!("{}", s_origin.capacity()); // capacity is at least 10+1, usually more
Iterating Over Strings
- Use the
charsmethod to access individual Unicode characters, andbytesto access each byte.
for c in "Зд".chars() {
println!("{c}");
}
Converting String to Other Types
- Convert to a byte array:
let s = String::from("hello");
let bytes = s.into_bytes();
- Convert to a string slice
&str:
let tmp_s = String::from("hello");
let s_str = tmp_s.as_str();