str通常被当作是&str的借用。str和String都是utf-8编码的。如果你想使用一个非utf-8编码的String,可以使用OsString。let mut s = String::new()let data = "initial contents";
let s = data.to_string();
let s = "initial contents".to_string();
let s = String::from("initial contents").let mut s = String::with_capacity(10);。当字符串长度小于10的时候,不会触发内存重分配。len方法查看字符串长度,通过capacity方法查看字符串容量。let s_from_vec = String::from_utf8(vec![0xe4, 0xbd, 0xa0, 0xe5, 0xa5, 0xbd]);。from_utf8_lossy,这将使用占位符替换不合法的utf8字符: let invalid_utf8 = vec![0xff, 0xff, 0xff];
let s_from_invalid_utf8 = String::from_utf8_lossy(&invalid_utf8);
Rust不允许使用下标访问字符串里面的单个字符
let mut s = String::from("foo");
s.push_str("bar");
// s is foobar
push_str方法不会改变字符串的所有权
let mut s = String::from("lo");
s.push('l');
// s is lol
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}");
let mut s_origin = String::with_capacity(10);
s_origin.push('1');
s_origin.reserve(10);
println!("{}", s_origin.capacity()); \\ 容量至少是10+1,一般会多分配一些
for c in "Зд".chars() {
println!("{c}");
}
let s = String::from("hello");
let bytes = s.into_bytes();
&strlet tmp_s = String::from("hello");
let s_str = tmp_s.as_str();