字符串

Rust 中,直接声明的字符串是字符串字面量格式&str,是切片的引用:

let s: &str = "aaa";

String是可变类型,&str是不可变引用。

str字符串切片是动态大小类型,编译器无法在编译器知道str类型的大小,因此无法直接使用,只能使用它的引用。

&str to String

  • "hello, world".into()
  • String::from("hello, world");
  • "hello, world".to_string()

String to &str

fn main() {
    let s = String::from("hello, world");
    say_hello(&s);
    say_hello(&s[..]);
    say_hello(s.as_str());
}
 
fn say_hello(s: &str) {
    println!("{}", s)
}

Push

let mut s = String::from("Hello ");
s.push_str("Rust");
// Hello Rust
println!("{}", s)

Insert

let mut s = String::from("Hello rust!");
s.insert(5, ',');
s.insert_str(6, " I like");
// Hello, I like rust!
println!("{}", s)

Replace

let string_replace = String::from("I like rust. Learning rust is my favorite!"); 
let new_string_replace = string_replace.replace("rust", "RUST");

Replacen

let string_replace = "I like rust. Learning rust is my favorite!";
// 替换1个
let new_string_replacen = string_replace.replacen("rust", "RUST", 1);

replace_range

Only for String, need mut:

let mut string_replace_range = String::from("I like rust!"); string_replace_range.replace_range(7..8, "R");

pop

fn main() { 
    let mut string_pop = String::from("rust pop 中文!"); 
    let p1 = string_pop.pop(); 
    let p2 = string_pop.pop(); 
    // p1 = Some( '!', ) 
    dbg!(p1); 
    // p2 = Some( '文', ) 
    dbg!(p2); 
    // string_pop = "rust pop 中"
    dbg!(string_pop); 
}

remove

fn main() {
    let mut string_remove = String::from("测试remove方法");
    // string_remove 占 18 个字节
    println!(
        "string_remove 占 {} 个字节",
        std::mem::size_of_val(string_remove.as_str())
    );
    // 删除第一个汉字
    string_remove.remove(0);
    // string_remove = "试remove方法"
    dbg!(string_remove);
}

truncate

fn main() {
    let mut string_truncate = String::from("测试truncate");
    string_truncate.truncate(3);
    // string_truncate = "测"
    dbg!(string_truncate);
}

clear

fn main() {
    let mut string_clear = String::from("string clear");
    string_clear.clear();
    // string_clear = ""
    dbg!(string_clear);
}

concatenate

+运算符相当于调用fn add(self, s: &str) -> String,因此:

  • 符号后的变量必须为&str类型
  • self在调用后会失去 所有权
fn main() {
    let s1 = String::from("hello,");
    let s2 = String::from("world!");
    // 在下句中,s1的所有权被转移走了,因此后面不能再使用s1
    let s3 = s1 + &s2;
    assert_eq!(s3,"hello,world!");
    // Error!
    println!("{}",s1)
}

format!

fn main() {
    let s1 = "hello";
    let s2 = String::from("rust");
    let s = format!("{} {}!", s1, s2);
    // hello rust!
    println!("{}", s)
}