Rust 入門 - String

新建一個空的 String

let mut s = String::new();

使用 to_string 方法從字符串字面值創(chuàng)建 String

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

使用 String::from 函數(shù)從字符串字面值創(chuàng)建 String

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

更新字符串

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

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

將字符串 slice 的內(nèi)容附加到 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 被移動了,不能繼續(xù)使用
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] 會發(fā)生什么呢?答案是: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);
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容