新建字符串

  1. // 新建空字符串
  2. let mut s = String::new();
  3. -------------------------------------
  4. let data = "initial contents";
  5. let s = data.to_string();
  6. // 该方法也可直接用于字符串字面值:
  7. let s = "initial contents".to_string();
  8. let s = String::from("initial contents");

更新字符串

  1. // 追加
  2. let mut s = String::from("foo");
  3. s.push_str("bar");
  4. let mut s1 = String::from("foo");
  5. let s2 = "bar";
  6. s1.push_str(s2);
  7. println!("s2 is {}", s2);
  8. let mut s = String::from("lo");
  9. s.push('l');
  10. // 使用 + 运算符
  11. let s1 = String::from("Hello, ");
  12. let s2 = String::from("world!");
  13. let s3 = s1 + &s2; // 注意 s1 被移动了,不能继续使用
  14. // 多个字符串
  15. let s1 = String::from("tic");
  16. let s2 = String::from("tac");
  17. let s3 = String::from("toe");
  18. let s = s1 + "-" + &s2 + "-" + &s3;
  19. // format!
  20. let s1 = String::from("tic");
  21. let s2 = String::from("tac");
  22. let s3 = String::from("toe");
  23. let s = format!("{}-{}-{}", s1, s2, s3);

Rust 的字符串不支持索引
**

字符串 slice

  1. let hello = "Здравствуйте";
  2. let s = &hello[0..4];

循环字符串

  1. for c in "नमस्ते".chars() {
  2. println!("{}", c);
  3. }
  4. for b in "नमस्ते".bytes() {
  5. println!("{}", b);
  6. }

String 与 &str

  • &str更像一个固定的数组,String像一个可变的数组。
  • String保留了一个len()和capacity(),但str只有一个len()。
  • &str 是 str的一个的borrowed 类型,可以称为一个字符串切片,一个不可变的string。

字符串转换

String => &str

  1. let e = &String::from("Hello Rust");
  2. // 或使用as_str()
  3. let e_tmp = String::from("Hello Rust");
  4. let e = e_tmp.as_str();
  5. // 不能直接这样使用
  6. // let e = String::from("Hello Rust").as_str();

&str => String

  1. let c = a.to_string();
  2. let d = String::from(b);
  3. let d = a.to_owned();

String + &str => String

  1. let mut strs = "Hello".to_string();
  2. // let mut strs = String::from("Hello");
  3. strs.push_str(" Rust");
  4. println!("{}", strs);

字符串对象常用的方法

方法 原型 说明
new() pub const fn new() -> String 创建一个新的字符串对象
to_string() fn to_string(&self) -> String 将字符串字面量转换为字符串对象
replace() pub fn replace<’a, P>(&’a self, from: P, to: &str) -> String 搜索指定模式并替换
as_str() pub fn as_str(&self) -> &str 将字符串对象转换为字符串字面量
push() pub fn push(&mut self, ch: char) 再字符串末尾追加字符
push_str() pub fn push_str(&mut self, string: &str) 再字符串末尾追加字符串
len() pub fn len(&self) -> usize 返回字符串的字节长度
trim() pub fn trim(&self) -> &str 去除字符串首尾的空白符
split_whitespace() pub fn split_whitespace(&self) -> SplitWhitespace 根据空白符分割字符串并返回分割后的迭代器
split() pub fn split<’a, P>(&’a self, pat: P) -> Split<’a, P> 根据指定模式分割字符串并返回分割后的迭代器。模式 P 可以是字符串字面量或字符或一个返回分割符的闭包
chars() pub fn chars(&self) -> Chars 返回字符串所有字符组成的迭代器

这些方法的示例用法推荐访问:简单教程-Rust基础教程