0

Rust中字符串操作

 5 months ago
source link: https://www.jdon.com/71810.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Rust中字符串操作

字符串数据类型是任何编程语言的非常重要的一部分。Rust 处理字符串的方式与其他语言略有不同。了解 Rust 中 String 和 str 之间的差异对于编写高效且内存安全的代码至关重要。

&str
Rust在核心语言中只有一种字符串类型,即字符串切片str,通常以其借用形式&str出现。

&str称为“字符串切片”,它始终指向合法的 UTF-8 序列。

let static_str: &str = "Hello, world!";
println(static_str);
// Output: Hello, world!

它们是一组字符,默认情况下是静态的。static_str一个具有固定大小的字符串文字,并且它是不可变的。

String 类型
Rust 中的 String 类型本质上是一个动态字节数组 (Vec)

let mut dynamic_str = String::from("Hello, ");
dynamic_str.push_str("Rust!");
println!("{}", dynamic_str);
// Output: Hello, Rust!

字符串操作
Rust 中有多种创建字符串的方法String:

  • 用于String::new()创建一个空字符串。
  • 使用字符串文字并用.to_string() 或String::from()进行转换。

String还提供了各种字符串操作的方法,例如:

1、附加字符串.push_str()

let mut dynamic_str = String::new();
dynamic_str.push_str("Hello World!");
println!("{}", dynamic_str);
// Output: Hello World!

2、连接字符串format!()

let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");

let s = format!("{}-{}-{}", s1, s2, s3);
println!("{}", s);
// Output: tic-tac-toe

3、替换子字符串.replace()

let s = String::from("Hello, world!");
let s = s.replace("world", "Rustaceans");
println!("{}", s);
// Output: Hello, Rustaceans!

4、使用.trim()修剪空白

let s = String::from("   Hello, world!   ");
let s = s.trim();
println!("{}", s);
// Output: Hello, world!
  • Rust 字符串默认采用 UTF-8 编码。
  • Rust 中的字符串字面量是 &str 类型,直接存储在可执行文件的内存中,因此访问起来高效、快速。
  • 创建新字符串会触发分配,这会影响运行时性能。因此,建议尽可能使用字符串片 (&str),以避免额外的分配。
  • 在许多其他编程语言中,通过索引引用字符串中的单个字符是一种有效且常见的操作。但是,如果尝试在 Rust 中使用索引语法访问字符串的部分内容,则会出现错误。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK