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
相关推荐
资源补给站1 小时前
大恒相机开发(2)—Python软触发调用采集图像
开发语言·python·数码相机
m0_748247551 小时前
Web 应用项目开发全流程解析与实战经验分享
开发语言·前端·php
刘大辉在路上1 小时前
突发!!!GitLab停止为中国大陆、港澳地区提供服务,60天内需迁移账号否则将被删除
git·后端·gitlab·版本管理·源代码管理
6.941 小时前
Scala学习记录 递归调用 练习
开发语言·学习·scala
FF在路上2 小时前
Knife4j调试实体类传参扁平化模式修改:default-flat-param-object: true
java·开发语言
众拾达人2 小时前
Android自动化测试实战 Java篇 主流工具 框架 脚本
android·java·开发语言
皓木.2 小时前
Mybatis-Plus
java·开发语言
不良人天码星2 小时前
lombok插件不生效
java·开发语言·intellij-idea
源码哥_博纳软云3 小时前
JAVA同城服务场馆门店预约系统支持H5小程序APP源码
java·开发语言·微信小程序·小程序·微信公众平台
学会沉淀。3 小时前
Docker学习
java·开发语言·学习