视频地址
头条地址:https://www.ixigua.com/i6765442674582356483
B站地址:https://www.bilibili.com/video/av78062009?p=1
网易云课堂地址:https://study.163.com/course/introduction.htm?courseId=1209596906#/courseDetail?tab=1
讲解内容
在rust核心语言中,只有一种字符串类型,就是str,意思就是string slice。通常,我们在rust语言中谈论string的时候通常包括str和标准库中的String。str和String都是UTF-8编码的。
0、创建一个空String
let mut s0 = String::new();
println!("s0 = {}", s0);
s0.push_str("Put something to empty string");
println!("s0 = {}", s0);
1、通过字面值创建一个String
(1)使用String的方式
let s11 = String::from("Create a string(s11)");
println!("s11 = {}", s11);
(2)使用str的方式
let s12 = "Create a string(s12)".to_string();
println!("s12 = {}", s12);
2、UTF-8编码
let s2 = String::from("你好");
println!("s2 = {}", s2);
3、更新String
3.1 使用 push_str:这种方式能添加一个str到String
let mut s3 = String::from("update string");
println!("before push, s3 = {}", s3);
s3.push_str(", push some thing");
println!("after push, s3 = {}", s3);
let s31 = ", push another";
s3.push_str(s31);
println!("after second push, s3 = {}", s3);
//push_str 并不会获取s31的所有权,接下来能继续使用
println!("after second push, s31 = {}", s31);
3.2 使用push:只能添加一个字符
let mut s32 = "lo".to_string();
println!("before push, s32 = {}", s32);
s32.push('l');
println!("after push, s32 = {}", s32);
3.3 使用 "+" 合并两个字符串
let s33 = String::from("hello");
let s34 = String::from("world");
let s35 = s33 + &s34;
println!("after +, s35 = {}", s35);
//println!("s33 = {}", s33); //报错,s33已经被移动
println!("s34 = {}", s34);
3.4 使用format! 链接多个字符串
let s341 = String::from("tic");
let s342 = String::from("tac");
let s343 = String::from("toe");
let s344 = format!("{}-{}-{}", s341, s342, s343); //format! 和 println!很想
let s345 = format!("{}{}{}", s341, s342, s343); // 此处仍然能使用 s341, s342, s343
println!("s344 = {}", s344);
println!("s345 = {}", s345);
4 索引String: rust 不支持字符串索引
let s4 = String::from("hello");
//let h = s4[0]; //错误
let s41 = "hello";
//let h2 = s41[0];//错误
//原因
let len1 = String::from("hello").len();
println!("len1 = {}", len1);
let len2 = String::from("你好").len();
println!("len2 = {}", len2); /期望的是 2 ?, 实际上 6, 一个UFT-8字符并不一定是一个确定的Unicode字符, 因此不能找到确定的索引
5 索引 str
let hello = "你好";
let h5 = &hello[0..3];
println!("h5 = {}", h5);
let s51 = "hello";
let h51 = &s51[0..1];
println!("h51 = {}", h51);
6 遍历
6.1 使用chars
let s61 = "你好";
for c in s61.chars() {
println!("{}", c);
}
println!("++++++++++++++++++++++++");
6.2 使用 bytes
for c in s61.bytes() {
println!("{}", c);
}