【Rust】String

String类

===========================================

1. push_str

2. as_bytes

3. push

4. chars

5. bytes

6. slice

============================================

定义字符串

// 不可变
let s = String::from("hello");
// 可变
let mut s = String::from("hello");

1. push_str

给末尾追加字符串

s.push_str("aaa");

2. as_bytes

将字符串转化为字节数组

let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {// 元素索引,元素引用
    if item == b' ' {
        return i;
    }
}
// iter 返回集合中的每一个元素,enumerate包装返回的结果

3. push

给末尾追加字符

s.push('a');

4. chars

返回char类型迭代器

for c in "hello".chars() {
    println!("{}", c);
}

5. bytes

返回byte类型迭代器

for b in "hello".bytes() {
    println!("{}", b);
}

6. slice

索引访问

let hello = "Здравствуйте";
let s = &hello[0..4];
println!("{}",s);
原文地址:https://www.cnblogs.com/yangchongxing/p/15773133.html