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
相关推荐
霍先生的虚拟宇宙网络2 分钟前
webp 网页如何录屏?
开发语言·前端·javascript
温吞-ing4 分钟前
第十章JavaScript的应用
开发语言·javascript·ecmascript
魔道不误砍柴功10 分钟前
实际开发中的协变与逆变案例:数据处理流水线
java·开发语言
鲤籽鲲18 分钟前
C# MethodTimer.Fody 使用详解
开发语言·c#·mfc
亚图跨际21 分钟前
Python和R荧光分光光度法
开发语言·python·r语言·荧光分光光度法
Rverdoser30 分钟前
RabbitMQ的基本概念和入门
开发语言·后端·ruby
dj244294570733 分钟前
JAVA中的Lamda表达式
java·开发语言
流星白龙1 小时前
【C++习题】10.反转字符串中的单词 lll
开发语言·c++
尘浮生1 小时前
Java项目实战II基于微信小程序的校运会管理系统(开发文档+数据库+源码)
java·开发语言·数据库·微信小程序·小程序·maven·intellij-idea
MessiGo1 小时前
Python 爬虫 (1)基础 | 基础操作
开发语言·python