gw_rust_programming_tutorial/chapter_8/
test_string.rs

1pub fn test_string() {
2    //新建字符串
3    let mut s = String::new();
4
5    //这新建了一个叫做 s 的空的字符串,接着我们可以向其中装载数据。通常字符串会有初始数据,因为我们希望一开始就有这个字符串。为此,可以使用 to_string 方法,它能用于任何实现了 Display trait 的类型,字符串字面量也实现了它。示例 8-12 展示了两个例子。
6    let data = "initial contents";
7
8    let s = data.to_string();
9
10    // 该方法也可直接用于字符串字面量:
11    let s = "initial contents".to_string();
12
13    //string是utf8存储的
14    let hello = String::from("السلام عليكم");
15    let hello = String::from("Dobrý den");
16    let hello = String::from("Hello");
17    let hello = String::from("שָׁלוֹם");
18    let hello = String::from("नमस्ते");
19    let hello = String::from("こんにちは");
20    let hello = String::from("안녕하세요");
21    let hello = String::from("你好");
22    let hello = String::from("Olá");
23    let hello = String::from("Здравствуйте");
24    let hello = String::from("Hola");
25
26    update_string();
27    test_slice();
28}
29
30//更新字符串
31fn update_string() {
32    //使用 push_str 和 push 附加字符串
33    let mut s = String::from("foo");
34    s.push_str("bar");
35
36    //使用 push_str 方法向 String 附加字符串 slice
37    let mut s1 = String::from("foo");
38    let s2 = "bar";
39    s1.push_str(s2);
40    println!("s2 is {}", s2);
41
42    //push 方法被定义为获取一个单独的字符作为参数,并附加到 String 中。示例 8-17 展示了使用 push 方法将字母 l 加入 String 的代码。
43    let mut s = String::from("lo");
44    s.push('l');
45    println!("s is {}", s);
46
47    //使用 + 运算符或 format! 宏拼接字符串
48    let s1 = String::from("Hello, ");
49    let s2 = String::from("world!");
50    let s3 = s1 + &s2; // 注意 s1 被移动了,不能继续使用
51
52    let s1 = String::from("tic");
53    let s2 = String::from("tac");
54    let s3 = String::from("toe");
55
56    let s = format!("{}-{}-{}", s1, s2, s3);
57    println!("s is {}", s);
58}
59
60//测试字符串切片
61fn test_slice() {
62    let hello = "Здравствуйте";
63
64    let s = &hello[0..4];
65    println!("slice s= {} len={}",s,hello.len());
66
67    //遍历字符串的方法
68    for c in hello.chars() {
69        println!("{}", c);
70    }
71
72    for c in hello.bytes() {
73        println!("{}", c);
74    }
75}