字符串
首先我们来看看什么是字符串,问题看似有点奇怪。字符串有什么好解释的,尤其在 java 和 javascript 语言中,code 随处可见。Rust在核心语言中只有一种 string(字符串)类型。
创建空字符串
fn main() {
let mut str0 = String::new();
str0.push_str("hello");
println!("str0 = {}",str0);
}
创建字符串
还是要说一说 rust 编译器比较智能
fn main() {
let str1 = String::from("hello");
let str2 = "world".to_string();
println!("str0 = {}",str1);
println!("str2 = {}",str2);
}
from::String
" ".to_string()
更新字符串
let mut str1 = String::from("hello");
str1.push_str(" world");
println!("str0 = {}",str1);
let mut str1 = String::from("hello");
let str2 = " world".to_string();
str1.push_str(&str2);
println!("str0 = {}",str1);
这里 push_str 是用了值并没有拿走所有权。
fn main() {
// let mut str0 = String::new();
// str0.push_str("hello");
let mut str1 = String::from("hello");
let str2 = " world".to_string();
str1.push_str(&str2);
println!("str0 = {}",str1);
println!("str2 = {}",str2);
}
push 添加字符而非字符串,并且只能使用单引号
let mut str3 = String::from("tutoria");
str3.push('l');
println!("str3 = {}",str3)
合并字符串
fn main() {
let str1 = String::from("hello");
let str2 = " world".to_string();
let str3 = str1 + &str2;
println!("str3 = {}",str3)
}
let str3 = str1 + &str2;
- 其实可以 s1 类具有 + 方法,str2 作为引用传入方法后所有 str1 就无法再使用了。
println!("str1 = {}",str1);
10 | println!("str1 = {}",str1);
| ^^^^ value borrowed here after move
format 宏
format! 宏和 println!,在 format 之后依旧可以使用 jsTut
fn main() {
let jsTut = String::from("javascript tut");
let mlTut = String::from("machine tut");
let rustTut = String::from("rust tut");
let tuts = format!("{},{},{}",jsTut,mlTut,rustTut);
println!("tuts = {} ",tuts);
}
索引
fn main() {
let tut = String::from("hello");
let tut_idx = tut[0];
}
字符串是不能被索引的,
error[E0277]: the type `std::string::String` cannot be indexed by `{integer}`
--> src/main.rs:5:19
|
5 | let tut_idx = tut[0];
| ^^^^^^ `std::string::String` cannot be indexed by `{integer}`
|
= help: the trait `std::ops::Index<{integer}>` is not implemented for `std::string::String`
fn main() {
let hello = "你好";
println!("len = {}",hello.len());
let h5 = &hello[0..3];
println!("{}",h5)
}
len = 6
你
遍历字符串
fn main() {
let str1 = String::from("hello");
for c in str1.chars(){
println!("c = {}",c);
}
}
按字节来打印输出字符串
fn main() {
let str1 = String::from("hello");
for b in str1.bytes(){
println!("b = {}",b);
}
}