【Rust】字符串String类型学习

什么是String

  • Rust的核心语言中只有一个String类型,那就是String slice,str通常被当作是&str的借用。
  • String类型是通过标准库提供的,而不是直接编码到核心语言中,它是一个可增长的、可变的、utf-8编码的类型。
  • strString都是utf-8编码的。如果你想使用一个非utf-8编码的String,可以使用OsString

创建新的String

  • String实际上是通过包装bytes类型的vector实现的。

  • 使用new方法创建String:let mut s = String::new()

  • 使用to_string方法创建String:

    rust 复制代码
    let data = "initial contents";
    let s = data.to_string();
    let s = "initial contents".to_string();
  • 使用String::from方法创建字符串,let s = String::from("initial contents").

  • 根据指定的容量,创建一个空字符串let mut s = String::with_capacity(10);。当字符串长度小于10的时候,不会触发内存重分配。

  • 可以通过len方法查看字符串长度,通过capacity方法查看字符串容量。

  • 通过utf-8类型的vector创建字符串let s_from_vec = String::from_utf8(vec![0xe4, 0xbd, 0xa0, 0xe5, 0xa5, 0xbd]);

  • 如果vector可能包含不合法的utf-8编码则可以用from_utf8_lossy,这将使用占位符替换不合法的utf8字符:

    rust 复制代码
        let invalid_utf8 = vec![0xff, 0xff, 0xff];
        let s_from_invalid_utf8 = String::from_utf8_lossy(&invalid_utf8);

更新String

Rust不允许使用下标访问字符串里面的单个字符

使用push_str和push追加字符串

rust 复制代码
let mut s = String::from("foo");
s.push_str("bar");
// s is foobar

push_str方法不会改变字符串的所有权

rust 复制代码
let mut s = String::from("lo");
s.push('l');
// s is lol

使用+操作符或者 format!宏连接字符串

rust 复制代码
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used
rust 复制代码
let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");

let s = format!("{s1}-{s2}-{s3}");

扩大字符串容量

rust 复制代码
let mut s_origin = String::with_capacity(10);
s_origin.push('1');
s_origin.reserve(10);
println!("{}", s_origin.capacity()); \\ 容量至少是10+1,一般会多分配一些

迭代字符串的方法

  • 可以使用chars方法访问独立的UniCode字符。使用bytes方法访问每一个字节。
rust 复制代码
for c in "Зд".chars() {
    println!("{c}");
}

将String类型转为其他类型

  • 转为bytes数组
rust 复制代码
let s = String::from("hello");
let bytes = s.into_bytes();
  • 转为字符串切片&str
rust 复制代码
let tmp_s = String::from("hello");
let s_str = tmp_s.as_str();
相关推荐
清水白石0083 分钟前
Python 性能优化全景解析:当 Big O 骗了你——深挖常数开销、内存与解释器黑盒
开发语言·python·性能优化
oi..6 分钟前
python Get/Post请求练习
开发语言·经验分享·笔记·python·程序人生·安全·网络安全
星夜夏空998 分钟前
C语言进阶项目——搭建内存池
c语言·开发语言
历程里程碑10 分钟前
Proto3 三大高级类型:Any、Oneof、Map 灵活解决复杂业务场景
java·大数据·开发语言·数据结构·elasticsearch·链表·搜索引擎
山楂树の15 分钟前
【计算机系统原理】Intel 与 AT&T 汇编指令格式转换
汇编·学习·缓存
小杍随笔16 分钟前
【Rust Exercism 练习详解:Anagram + Space Age + Sublist(附完整代码与深度解读)】
开发语言·rust·c#
第二只羽毛18 分钟前
IO代码解释3
java·大数据·开发语言
是娇娇公主~23 分钟前
C++迭代器详解
开发语言·c++·stl
qq_1481153723 分钟前
C++网络编程(Boost.Asio)
开发语言·c++·算法
weisian15123 分钟前
Java并发编程--24-死锁排查与性能调优:线上并发问题诊断指南(死锁,CPU飙升,内存溢出)
java·开发语言·arthas·死锁·火焰图·cpu飙升