Rust 入门 - String

新建一个空的 String

let mut s = String::new();

使用 to_string 方法从字符串字面值创建 String

let data = "init";
let s = data.to_string();
let s = "str".to_string();

使用 String::from 函数从字符串字面值创建 String

let s = String::from("hello");

更新字符串

使用 push_str 方法向 String 附加字符串 slice

let mut s = String::from("hello");
s.push_str("world");

将字符串 slice 的内容附加到 String 后使用它

let mut s1 = String::from("hello");
let s2 = "world";
s1.push_str(s2);
println!("s2 = {}", s2);

使用 push 将一个字符加入 String 值中

let mut s = String::from("hell");
s.push('o');
println!("s = {}", s);

使用 + 运算符将两个 String 值合并到一个新的 String 值中

let s1 = String::from("hello");
let s2 = String::from("world");
let s3 = s1 + " " + &s2; //  注意 s1 被移动了,不能继续使用
println!("s3 = {}", s3);

多个字符串相加

let s1 = "hello";
let s2 = "world";
let s3 = "!";
let s = format!("{}-{}-{}", s1, s2, s3);
println!("s = {}", s);

字符串 slice

let hello = "Здравствуйте";
let s = &hello[0..4];
println!("s = {}", s);
//如果获取 &hello[0..1] 会发生什么呢?答案是:Rust 在运行时会 panic,就跟访问 vector 中的无效索引时一样thread 'main' panicked at 'byte index 1 is not a char boundary; it is inside 'З' (bytes 0..2) of `Здравствуйте`', src/main.rs:40:14

遍历字符串

for c in "नमस्ते".chars() {
    println!("{}", c);
}

for b in "नमस्ते".bytes() {
    println!("{}", b);
}

推荐阅读更多精彩内容

  • Slice 另一个没有所有权的数据类型是 slice。slice 允许你引用集合中一段连续的元素序列,而不用引用整...
    Lee_dev阅读 441评论 0 0
  • 视频地址 头条地址:https://www.ixigua.com/i6765442674582356483B站地址...
    令狐壹冲阅读 128评论 0 1
  • 通用编程概念 变量与可变性 变量默认不可变,如需要改变,可在变量名前加 mut 使其可变。例如:let mut a...
    soojade阅读 12,180评论 2 30
  • 简介 接上回 了解Rust 字符串首先要区分两个概念,一个是字符串字面值,另外一个是字符串本身,这个在参数传递时是...
    kami1983阅读 3,026评论 0 2
  • 一、简介 Rust是Mozilla公司推出的一门全新的编程语言,1.0版本于2015年5月15日正式对外发布。作为...
    区块链习生阅读 2,028评论 1 1