Rust语言之字符串

文章目录


Rust语言设计官方教程

一、字符

Rust提供char为字符存储变量类型,与其他语言不同的是,char占4位,存储的是Unicode字符。
由于Rust中限制比较严格,所以Ascii码和字符直接的转换需要指定每个数据的类型

rust 复制代码
fn main() {
    let mut s = 'c';
    println!("value:{}",s); //value:c
    s = 65u8 as char;
    println!("1.after:{}",s);//1.after:A
    let i:u8 = 'a' as u8;
    s = i as char;
    println!("char:{},ascii:{}",s,i);//char:a,ascii:97
}

二、字符串

Rust语言中,字符串分为两种&str 和 string

  • &str 是一种引用类型,是无法修改字符串的内容
  • string 是标准库中提供的一个存储方式,可以对字符串进行修改、追加等操作

1.&str

rust 复制代码
fn main() {
    let s:&str = "hello world";
    println!("s value:{}",s); //s value:hello world
}

2.string

字符串(String)类型由 Rust 标准库提供,而不是编入核心语言,它是一种可增长、可变、可拥有、UTF-8 编码的字符串类型。

创建字符串

rust 复制代码
fn main() {
    let mut s = String::new(); //创建一个空字符串
    s.push_str("hello"); //追加字符串
    println!("s value:{}",s); //s value:hello

    let s1 = String::from("hello");
    println!("s1 value:{}",s1); //s1 value:hello

    let s_t = "hello";
    let s2 = s_t.to_string();
    println!("s2 value:{}",s2); //s2 value:hello
}

遍历字符串

rust 复制代码
# chars方法:
fn main() {
    let s = "hello,world!".to_string();
    for i in s.chars(){
        println!("value:{}",i);
    }
}
value:h
value:e
value:l
value:l
value:o
value:,
value:w
value:o
value:r
value:l
value:d
value:!

# bytes方法
fn main() {
    let s = "hello,world!".to_string();
    for i in s.bytes(){
        println!("ascii value:{}",i);
    }
}
ascii value:104
ascii value:101
ascii value:108
ascii value:108
ascii value:111
ascii value:44
ascii value:119
ascii value:111
ascii value:114
ascii value:108
ascii value:100
ascii value:33

变更字符串

rust 复制代码
# replace 方法
fn main() {
    let mut s = String::from("Hello, world!");  
    println!("value : {}",s);  // Hello, world!
    s = s.replace("world", "Rust");  
    println!("after : {}", s); // Hello, Rust!
}

指定位置插入字符串

rust 复制代码
# insert_str 方法
fn main(){
    let mut s = String::from("world");  
    s.insert_str(3, " Hello ");  
    println!("{}", s); // wor Hello ld
}

字符串拼接

rust 复制代码
# 使用+号
fn main(){
    let s1 = String::from("Hello, ");
    let s2 = String::from("world!");
    let s3 = s1 + &s2; 
    println!("{}",s3); //Hello, world!
}

注意:&符号是引用,s1前面没有加&,所以s1后面不能再用了

rust 复制代码
fn main(){
    let s1 = String::from("Hello, ");
    let s2 = String::from("world!");
    let s3 = s1 + &s2; 
    println!("{}",s3); //Hello, world!
    println!("{}",s1);
}
Compiling hello v0.1.0 (/home/kali/Desktop/ctf/script/RustPro/hello)
error[E0382]: borrow of moved value: `s1`
 --> src/main.rs:6:19
  |
2 |     let s1 = String::from("Hello, ");
  |         -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait
3 |     let s2 = String::from("world!");
4 |     let s3 = s1 + &s2; 
  |              -- value moved here
5 |     println!("{}",s3); //Hello, world!
6 |     println!("{}",s1);
  |                   ^^ value borrowed here after move
  |
  = 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)
help: consider cloning the value if the performance cost is acceptable
  |
4 |     let s3 = s1.clone() + &s2; 
  |                ++++++++

For more information about this error, try `rustc --explain E0382`.
error: could not compile `hello` (bin "hello") due to 1 previous error

解决方法:

  • 使用硬拷贝 :let s3 = s1.clone() + &s2;

宏拼接(format!)

rust 复制代码
fn main(){
    let s1 = "hello";
    let s2 = "world";
    let s3 = format!("{},{}!",s1,s2);
    println!("value : {}",s3); // value : hello,world!
    println!("s1 :{}; s2 :{}",s1,s2); //s1 :hello; s2 :world
}

三、切片

切片(slice)允许你引用集合中一段连续的元素序列,而不用引用整个集合。

1.字符串切片

rust 复制代码
fn main(){
    let s1 = String::from("Hello, world!");
    let answer = &s1[0..5];
    println!("{}",answer); // Hello
}

2.数组(向量)切片

rust 复制代码
fn main(){
    let mut vec = vec![1,2,3,4,5];
    let slice = &mut vec[1..3];
    println!("slice value:{:?}",slice); // [2,3]
    slice[0]=100;
    println!("slice after:{:?}",slice); // [100,3]
    println!("vce after:{:?}",vec); //[1,100,3,4,5]
}

由于切片是引用类型,所以修改了切片就等于修改了原数组向量;又因为字符串(String)是一个由字符组成的集合,但不同于其他一些语言,Rust中的字符串不是通过索引直接访问其字符的简单字节数组。所以不能通过这种方式去修改string。

rust 复制代码
fn main(){
    let mut s1 = String::from("Hello, world!");
    let answer = &mut s1[0..5];
    println!("{}",answer); // Hello
    answer[0] ='S';
    println!("{}",answer)
}

  Compiling hello v0.1.0 (/home/kali/Desktop/ctf/script/RustPro/hello)
error[E0277]: the type `str` cannot be indexed by `{integer}`
 --> src/main.rs:5:12
  |
5 |     answer[0] ='S';
  |            ^ string indices are ranges of `usize`
  |
  = help: the trait `SliceIndex<str>` is not implemented for `{integer}`
  = note: you can use `.chars().nth()` or `.bytes().nth()`
          for more information, see chapter 8 in The Book: <https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings>
  = help: the trait `SliceIndex<[_]>` is implemented for `usize`
  = help: for that trait implementation, expected `[_]`, found `str`
  = note: required for `str` to implement `Index<{integer}>`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `hello` (bin "hello") due to 1 previous error
相关推荐
007php00744 分钟前
服务器上PHP环境安装与更新版本和扩展(安装PHP、Nginx、Redis、Swoole和OPcache)
运维·服务器·后端·nginx·golang·测试用例·php
艾莉丝努力练剑3 小时前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
武子康4 小时前
Java-72 深入浅出 RPC Dubbo 上手 生产者模块详解
java·spring boot·分布式·后端·rpc·dubbo·nio
椰椰椰耶5 小时前
【Spring】拦截器详解
java·后端·spring
brzhang6 小时前
我操,终于有人把 AI 大佬们 PUA 程序员的套路给讲明白了!
前端·后端·架构
倔强青铜37 小时前
苦练Python第18天:Python异常处理锦囊
开发语言·python
u_topian7 小时前
【个人笔记】Qt使用的一些易错问题
开发语言·笔记·qt
珊瑚里的鱼8 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
AI+程序员在路上8 小时前
QTextCodec的功能及其在Qt5及Qt6中的演变
开发语言·c++·qt