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);

 

相关文章:

  • 2022-12-23
  • 2021-07-19
  • 2021-06-04
  • 2021-05-21
  • 2022-02-28
  • 2021-10-21
  • 2022-02-02
  • 2022-12-23
猜你喜欢
  • 2021-05-23
  • 2021-09-24
  • 2022-01-05
  • 2021-05-19
  • 2022-02-14
  • 2021-08-10
相关资源
相似解决方案