Rust 中的字符串
创建
// 字符串字面量, 类型为: &str, 从定义到整个程序的结束一直存在
let s1 = "hello world";
// 创建一个空字符串对象
let s2 = String::new();
// 从一个字符串字面量创建一个字符串对象
let s3 = String::from(s1);
处理函数
获取字符串的长度:len()
// 获取字符串长度
let s1 = "hello world";
let s2 = String::from(s1);
println!("s1.len = {}, s2.len = {}", s1.len(), s2.len());
//> s1.len = 11, s2.len = 11
获取字符串对象的字面量:as_str()
let s1 = "hello world";
let s2 = String::from(s1);
println!("s2: {}", s2.as_str());
//> s2: hello world
追加一个字符串字面量到字符串对象:push_str()
let mut s1 = String::new();
s1.push_str("hello");
s1.push_str(" world");
println!("s1: {}", s1);
//> s1: hello world
追加一个字符到字符串对象:push()
let mut s1 = String::new();
s1.push('O');
s1.push('k');
println!("s1: {}", s1);
//> s1: Ok
去除字符串首尾的空白字符:trim()
let s1 = String::from(" \r\nhello, world! \r\n ");
let s2 = s1.trim();
println!("s1.len: {}, s2.len: {}", s1.len(), s2.len());
//> s1.len: 22, s2.len: 13
字符串分割(返回一个分割后的迭代器):split()
let s1 = String::from("hello,world,!!!");
for s in s1.split(',') {
println!("{}", s);
}
/*>
hello
world
!!!
*/
获取字符串中的每一个字符:chars()
let s1 = String::from("hello");
for c in s1.chars() {
println!("{}", c);
}
/*>
h
e
l
l
o
*/
字符串的拼接:add()
,+
使用
add()
use std::ops::Add;
let s1 = String::from("hello");
let s2 = s1.add(" world");
println!("{}", s2);
//> hello world
使用
+
let s1 = String::from("hello");
let s2 = String::from(" world");
let s3 = s1 + &s2;
println!("{}", s3);
//> hello world
评论区