Rust 程式設計視訊教程對應講解內容-String

linghuyichong發表於2019-12-29

頭條地址:https://www.ixigua.com/i676544267458235648...
B站地址:https://www.bilibili.com/video/av78062009?...
網易雲課堂地址:https://study.163.com/course/introduction....

在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);
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

令狐一衝

相關文章