定义

str

Rust核心中只有一种字符串类型:str,它经常以借用的形式出现:&str(字符串slice),并且被存储在二进制文件

String

String由标准库提供,它可增长、可变、有所有权

这两种类型都是UTF-8编码的

Rust标准库中,有很多&strString的变体,通常以它们为后缀作为区分,分别代表可借用的有所有权的类型

新建、修改

新建

  • let mut s = String::**new**();
  • let mut s2 = String::**from**("hello");
  • let mut s3 = "hello".**to_string**();

修改

使用push_str()

  1. let mut s1 = String::from("foo");
  2. let s2 = "bar";
  3. s1.push_str(s2); println!("s2 is {}", s2);

使用push()附加单个字符

  1. let mut s = String::from("lo");
  2. s.push('l');

拼接

使用 **+** 拼接

+操作符会为第一个参数调用add方法,根据参数签名:
fn add(self, s: &str) -> String {
这会获取第一个参数的所有权,但是只需要第二个参数的引用

  1. let s1 = String::from("Hello, ");
  2. let s2 = String::from("world!");
  3. let s3 = s1 + &s2; // 注意 s1 被移动了,不能继续使用

使用**format!**拼接

  1. let s1 = String::from("tic");
  2. let s2 = String::from("tac");
  3. let s3 = String::from("toe");
  4. let s = format!("{}-{}-{}", s1, s2, s3);

String的存储

String内部使用 Vec<u8>存储,即将字符串的Unicode转换为字节后存储在Vector

可以使用字符串slice来获取字符,但是需要自己计算清楚字符的字节范围,否则可能报错

可以使用chars()方法获取字符串的迭代器,逐个取字符

  1. for c in "你好".chars() {
  2. println!("{}", c);
  3. }