# rust abc(6): 字符串的简单使用

news2024/7/4 6:06:02

在这里插入图片描述

文章目录

    • 1. 目的
    • 2. 数据类型
      • 2.1 str 类型
      • 2.2 标准库 `String` 类型
    • 3. 常用 API
      • 3.1 `len()` 方法
      • 3.2 `is_empty()` 方法
      • 3.3 `starts_with()` 方法
      • 3.4 `find()` 方法
    • 4. References

1. 目的

学习 Rust 语言中的字符串, 包括数据类型, 常用 API。

2. 数据类型

Rust 语言提供了两种字符串:

  1. str 类型. 通常用它的 borrow 类型 &str.

  2. 标准库的 String 类型.

2.1 str 类型

也叫做 string slice. 通常是使用它的 borrow 类型,也就是 &str. 1

字符串字面量 (string literals) 的类型, 也是 str 类型(也就是 &'static str).

字符串字面量 &str 是在编译时确定其值的字符串类型。

fn main() {
    let a:&str = "hello";
    println!("a {}", a);

    let b = "world";
    println!("b {}", b);
}

编译运行

zz@Legion-R7000P% ./u1
a hello
b world

2.2 标准库 String 类型

Rust 语言的 String 位于标准库2:

在这里插入图片描述

String 是一个 struct3:

在这里插入图片描述

pub struct String {
    vec: Vec<u8>,
}

其中 Vec<u8> 指的是 UTF-8 字符作为元素的容器。这里暂时不了解容器,简单理解为:和 C++ 的 vector 类似的东西。

尝试使用 String 创建字符串变量:

fn main() {
    let s1 = String::new(); // 创建空字符串
    println!("s1: |{}|", s1);

    let s2 = String::from("hello world"); // 从字符串字面量创建 String
    println!("s2: {}", s2);
}

3. 常用 API

3.1 len() 方法

无论是 &str 还是 String 类型的对象, 都支持 len() 方法:

u3.rs:

fn main() {
    let s1 = String::new();
    println!("s1: |{}|, s1.len(): {}", s1, s1.len());

    let s2 = String::from("hello world");
    println!("s2: {}, s2.len(): {}", s2, s2.len());

    let t1 = "";
    println!("t1: |{}|, t1.len(): {}", t1, t1.len());

    let t2 = "hello world";
    println!("t2: {}, t2.len(): {}", t2, t2.len());
}

编译运行结果:

zz@Legion-R7000P% rustc u3.rs
zz@Legion-R7000P% ./u3
s1: ||, s1.len(): 0
s2: hello world, s2.len(): 11
t1: ||, t1.len(): 0
t2: hello world, t2.len(): 11

3.2 is_empty() 方法

无论是 &str 还是 String 类型的对象, 都支持 is_empty() 方法:

u4.rs:

fn main() {
    let s1 = String::new();
    println!("s1: |{}|, s1.is_empty(): {}", s1, s1.is_empty());

    let s2 = String::from("hello world");
    println!("s2: {}, s2.is_empty(): {}", s2, s2.is_empty());

    let t1 = "";
    println!("t1: |{}|, t1.is_empty(): {}", t1, t1.is_empty());

    let t2 = "hello world";
    println!("t2: {}, t2.is_empty: {}", t2, t2.is_empty());
}

编译运行结果:

zz@Legion-R7000P% rustc u4.rs
zz@Legion-R7000P% ./u4
s1: ||, s1.is_empty(): true
s2: hello world, s2.is_empty(): false
t1: ||, t1.is_empty(): true
t2: hello world, t2.is_empty: false

3.3 starts_with() 方法

无论是 &str 还是 String 类型的对象, 都支持 starts_with() 方法, 也都支持 ends_with() 方法。这里以及 starts_with() 方法为例:

u5.rs:

fn main() {
    let s1 = String::from("Hello World");
    println!("s1: {}, s1.starts_with(\"Hello\"): {}", s1, s1.starts_with("Hello"));
    println!("s1: {}, s1.starts_with(\"hello\"): {}", s1, s1.starts_with("hello"));

    let t1 = "Hello World";
    println!("t1: {}, t1.starts_with(\"Hello\"): {}", t1, t1.starts_with("Hello"));
    println!("t1: {}, t1.starts_with(\"hello\"): {}", t1, t1.starts_with("hello"));
}

编译运行结果:

zz@Legion-R7000P% rustc u5.rs
zz@Legion-R7000P% ./u5   
s1: Hello World, s1.starts_with("Hello"): true
s1: Hello World, s1.starts_with("hello"): false
t1: Hello World, t1.starts_with("Hello"): true
t1: Hello World, t1.starts_with("hello"): false

3.4 find() 方法

无论是 &str 还是 String 类型的对象, 都支持 find() 方法, 返回的是匹配到给定模式时当前 &str/string 的第一个字符的索引. 举例如下:

这里本来想写一个简单的例子, 不过编译报错了, 看起来 rust 的 println! 宏罢工了, 不能直接处理字符串的 find() 方法返回的结果:

在这里插入图片描述

对应的代码是 u6.rs(这是一个错误的示范, 了解的大佬欢迎在评论区赐教)

fn main() {
    let s1 = String::from("Hello World");
    let idx1 = s1.find("ello");
    let idx2 = s1.find("world");
    println!("s1: {}, s1.find(\"ello\"): {}", s1, idx1);
    println!("s1: {}, s1.find(\"world\"): {}", s1, idx2);

    let t1 = "Hello World";
    let idx1 = t1.find("ello");
    let idx2 = t1.find("world");
    println!("t1: {}, t1.find(\"ello\"): {}", t1, idx1);
    println!("s1: {}, s1.find(\"world\"): {}", s1, idx2);
}
zz@Legion-R7000P% rustc u6.rs
error[E0277]: `Option<usize>` doesn't implement `std::fmt::Display`
 --> u6.rs:5:51
  |
5 |     println!("s1: {}, s1.find(\"ello\"): {}", s1, idx1);
  |                                                   ^^^^ `Option<usize>` cannot be formatted with the default formatter
  |
  = help: the trait `std::fmt::Display` is not implemented for `Option<usize>`
  = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
  = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0277]: `Option<usize>` doesn't implement `std::fmt::Display`
 --> u6.rs:6:52
  |
6 |     println!("s1: {}, s1.find(\"world\"): {}", s1, idx2);
  |                                                    ^^^^ `Option<usize>` cannot be formatted with the default formatter
  |
  = help: the trait `std::fmt::Display` is not implemented for `Option<usize>`
  = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
  = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0277]: `Option<usize>` doesn't implement `std::fmt::Display`
  --> u6.rs:11:51
   |
11 |     println!("t1: {}, t1.find(\"ello\"): {}", t1, idx1);
   |                                                   ^^^^ `Option<usize>` cannot be formatted with the default formatter
   |
   = help: the trait `std::fmt::Display` is not implemented for `Option<usize>`
   = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
   = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0277]: `Option<usize>` doesn't implement `std::fmt::Display`
  --> u6.rs:12:52
   |
12 |     println!("s1: {}, s1.find(\"world\"): {}", s1, idx2);
   |                                                    ^^^^ `Option<usize>` cannot be formatted with the default formatter
   |
   = help: the trait `std::fmt::Display` is not implemented for `Option<usize>`
   = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
   = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

error: aborting due to 4 previous errors

For more information about this error, try `rustc --explain E0277`.

4. References


  1. https://doc.rust-lang.org/std/primitive.str.html ↩︎

  2. https://doc.rust-lang.org/std/string/struct.String.html# ↩︎

  3. https://doc.rust-lang.org/src/alloc/string.rs.html#365 ↩︎

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/693021.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

新手入门:从零搭建vue3+webpack实战项目模板

搭建一个 vue3 webpack5 element-plus 基本模板 &#xff08;vue3 webpack5 从零配置项目&#xff09;。 本项目结构可以作为实战项目的基本结构搭建学习&#xff0c;作为刚学习完vue还没有实战项目经验的小伙伴练习比较合适。 项目地址&#xff1a; GitHub&#xff1a;ht…

如何将手写笔记转换成电子版格式?

记笔记是一种非常有效的学习方法。它不仅可以帮助我们加深对所学内容的理解&#xff0c;还能让我们收集更多有用的信息&#xff0c;以方便后续的查看和复习。不过&#xff0c;用传统的纸质笔记本记录笔记存在一定的弊端&#xff0c;比如说不易保存、不易携带等等。所以&#xf…

Mac下的java.io.FileNotFoundException: ~/Desktop/a.sql (No such file or directory)

【问题】&#xff1a; 今天在运行一个文件读取的Demo时&#xff0c;报如下错误: java.io.FileNotFoundException: ~/Desktop/a.sql (No such file or directory)如下图所示 &#xff1a; 可是这个文件命名可以通过终端窗口访问到啊&#xff1f; 【解决方案】&#xff…

STM32外设系列—HC-SR04(超声波)

文章目录 一、超声波测距基本原理二、超声波传感器简介三、HC-SR04测距实现思路四、超声波测距程序实现4.1 HC-SR04初始化程序4.3 TIM开关程序4.4 获取定时时间4.5 计算测量距离4.6 宏定义 五、应用实例六、拓展应用 一、超声波测距基本原理 超声波测距的原理非常简单&#xf…

高压放大器在压电陶瓷驱动器中的应用

高压放大器是一种将低电压信号放大成高电压信号的电子设备。它广泛运用于各种领域&#xff0c;如医疗、工业、军事以及科学研究。压电陶瓷驱动器是一种利用压电效应来驱动机械运动的装置。这两种设备经常被用于控制和操作许多不同类型的系统。 压电陶瓷是一种能够将电能转化为机…

监控摄像头的像素200万,400万,800万都是什么意思,200万像素、400万像素、800万像素是如何换算出来的?

一、像素 像素&#xff08;Pixel&#xff09;是用来表示图像分辨率的单位&#xff0c;数字越大&#xff0c;表示图像中的细节可以更精细地展现。当我们谈论监控摄像头的像素时&#xff0c;通常指的是摄像头图像传感器上的像素数量。像素的数量可以通过传感器上的横向像素数乘以…

win如何使用OpenSSL生成自签名证书,使 http 升级为 https

win如何使用OpenSSL生成自签名证书&#xff0c;使 http 升级为 https 前言 HTTPS其实就是HTTP over SSL&#xff0c;也就是让HTTP连接建立在SSL安全连接之上。 创建自签名证书需要安装openssl。参考本文安装OpenSSL部分。 使用OpenSSL生成自签名证书的步骤&#xff1a;参考…

python spider 爬虫 之 Selenium 系列 (-) Selenium

京东的 seckill 秒杀 专区 用 urllib 是获取不到的 回顾一下urllib 爬虫 # urllib 爬虫 from urllib import request headers {} url # 请求定制 req request(urlurl, headers headers) # 模拟请求 response request(req) content response.read().decode(utf-…

windows下安装Visual Studio + CMake+OpenCV + OpenCV contrib

目录 1 安装visual studio 2 安装CMake 3 OpenCV源码安装 3.1 OpenCV源码下载 3.2 OpenCV contrib源码下载 3.3 安装OpenCV 3.4 安装OpenCV-crontrib 3.5 VS生成代码 4 环境配置 最近在研究windows系统上部署安装目标检测算法&#xff0c;需要用到OpenCV软件&#xff…

智能指针+拷贝构造+vector容器+多态引起的bug

今天在调试一段代码的时候&#xff0c;VC编译提示&#xff1a; error C2280: “T485CommCtrlPara::T485CommCtrlPara(const T485CommCtrlPara &)”: 尝试引用已删除的函数 函数执行部分如下&#xff1a; 看意思是这个pComm485Pro已经消亡了&#xff0c;后续push_back到ve…

高速电路设计系列分享-信号链精度分析(中)

目录 概要 整体架构流程 技术名词解释 技术细节 1.直流无源误差 小结 概要 提示&#xff1a;这里可以添加技术概要 在任何设计中&#xff0c;信号链精度分析都可能是一项非常重要的任务&#xff0c;必须充分了解。之前&#xff0c; 我们讨论了在整个信号链累积起来并且最终会…

统一日志处理----AOP/面向切面编程

AOP Aspect Oriented Programing&#xff1a;面向切面编程 AOP是对OOP的补充&#xff0c;进一步提高编程的效率 AOP的常见使用场景有&#xff1a;权限检查、记录日志、事务管理等 如下图所示结构&#xff0c;每个模块都含有相同的系统需求&#xff0c;而这些需求和模块本身的功…

Flutter进阶-动画详解

目录 动画类别 一、隐式&#xff08;全自动&#xff09;动画 二、显式动画&#xff08;手动控制&#xff09; 三、其他动画(CustomPainter) 动画类别 Flutter 中有多种类型的动画&#xff1a; 隐式动画&#xff1a;通过更改部件属性自动触发的预定义动画&#xff0c;例如 …

什么是cookie

1、cookie是什么 Cookie&#xff0c;有时也用其复数形式Cookies。类型为“小型文本文件”&#xff0c;是某些网站为了辨别用户身份&#xff0c;进行Session跟踪而储存在用户本地终端上的数据&#xff08;通常经过加密&#xff09;&#xff0c;由用户客户端计算机暂时或永久保存…

Python强类型编程

Python是一门强类型的动态类型语言&#xff0c;具体如下特性&#xff1a; 可以动态构造脚本执行、修改函数、对象类型结构、变量类型但不允许类型不匹配的操作 第一个例子体现动态性&#xff1a;用字符串直接执行代码&#xff0c;动态构建了一个函数并执行&#xff0c;甚至给…

力扣744.寻找比目标字母大的最小字符(java暴力查找法,二分查找法)

题目描述&#xff1a; 给你一个字符数组 letters&#xff0c;该数组按非递减顺序排序&#xff0c;以及一个字符 target。letters 里至少有两个不同的字符。 返回 letters 中大于 target 的最小的字符。如果不存在这样的字符&#xff0c;则返回 letters 的第一个字符。 [外链…

岭回归(Ridge)不同alpha值对归回结果的影响

对于有些矩阵&#xff0c;矩阵中某个元素的一个很小的变动&#xff0c;会引起最后计算结果误差很大&#xff0c;这种矩阵称为“病态矩阵”。有些时候不正确的计算方法也会使一个正常的矩阵在运算中表现出病态。对于高斯消去法来说&#xff0c;如果主元&#xff08;即对角线上的…

亚马逊测评:如何有效使用IP和养号设备环境

随着网络科技的崛起&#xff0c;越来越多的本土企业入驻亚马逊电子商务平台上&#xff0c;这导致了对产品评价需求的激增。然而&#xff0c;评价并非随意进行&#xff0c;它需要多方面的资源&#xff0c;并需要密切注意一些重要环节。以下是我分享给大家一些宝贵的知识&#xf…

如何实现敏捷交付中的自动化测试优化

在提及自动化测试的时候&#xff0c;很多人会把工具的使用等同于自动化测试。自动化测试应该是一个策略性的系统化工程&#xff0c;不只有自动化工具。自动化测试要发挥其频繁快速的质量反馈作用&#xff0c;还需要团队从文化和技术上去建设和学习。 提到敏捷交付&#xff0c;…

数据库监控与调优【十二】—— JOIN语句优化

JOIN语句优化-JOIN种类、算法与原理 JOIN的种类 笛卡尔连接&#xff08;cross join&#xff09; -- 举例&#xff1a;通过笛卡尔连接查询两张表的结果集和单查两张表的结果集对比 SELECT count( * ) FROM users a CROSS JOIN orders b; SELECT ( SELECT count( * ) FROM user…