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
相关推荐
Qter_Sean11 分钟前
自己动手写Qt Creator插件
开发语言·qt
何曾参静谧16 分钟前
「QT」文件类 之 QIODevice 输入输出设备类
开发语言·qt
爱吃生蚝的于勒1 小时前
C语言内存函数
c语言·开发语言·数据结构·c++·学习·算法
码上一元2 小时前
SpringBoot自动装配原理解析
java·spring boot·后端
小白学大数据3 小时前
Python爬虫开发中的分析与方案制定
开发语言·c++·爬虫·python
冰芒猓4 小时前
SpringMVC数据校验、数据格式化处理、国际化设置
开发语言·maven
失落的香蕉4 小时前
C语言串讲-2之指针和结构体
java·c语言·开发语言
枫叶_v4 小时前
【SpringBoot】22 Txt、Csv文件的读取和写入
java·spring boot·后端
红中马喽4 小时前
JS学习日记(webAPI—DOM)
开发语言·前端·javascript·笔记·vscode·学习
杜杜的man5 小时前
【go从零单排】Closing Channels通道关闭、Range over Channels
开发语言·后端·golang