字符串

Rust 的核心语言中只有一种字符串类型:str,字符串 slice,它通常以被借用的形式出现,&str

新建字符串


#![allow(unused)]
fn main() {
let mut s = String::new();
let s = "initial contents".to_string();
let s = String::from("initial contents");
}

更新字符串


#![allow(unused)]
fn main() {
let mut s = String::from("foo");
s.push_str("bar");

 // 追加一个字符,结果lol
 let mut s = String::from("lo");
 s.push('l');
 
 // 使用 + 运算符或 format! 宏拼接字符串
 let s1 = String::from("Hello, ");
 let s2 = String::from("world!");
 let s3 = s1 + &s2; 
 
 // format! 宏拼接字符串
 let s = format!("{}-{}-{}", s1, s2, s3);
}

索引字符串


#![allow(unused)]
fn main() {
let s1 = String::from("hello");
let h = s1[0];
let s = &hello[0..4];
}

遍历字符串的方法


#![allow(unused)]
fn main() {
for c in "abc".chars() {
    println!("{}", c);
}
for b in "abc".bytes() {
    println!("{}", b);
}
}