fn main() {
    let  s = String::from("hello dj");
    //字符串字面值实际就是字符串的切片,所以
    let ss ="hello dj";
    //&s[..]其实等价于ss
    let s1 = first_word(&s[..]);
    println!("s1 is {}",s1);

    let s2 = first_word(ss);
    println!("s2 is {}",s2);
}
//&str是字符串 slice 类型
fn first_word(s: &str) -> &str {
    //as_bytes 方法将 String 转化为字节数组
    let bytes = s.as_bytes();
    //通过enumerate获取了元素的索引,和值的引用的所以使用&item。
    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }
    //返回整个字符串的切片
    &s[..]
}

相关文章:

  • 2022-12-23
  • 2021-07-07
  • 2022-02-26
  • 2022-12-23
  • 2022-01-14
  • 2022-12-26
  • 2021-12-08
  • 2022-02-04
猜你喜欢
  • 2021-07-08
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-10
  • 2022-12-23
  • 2021-12-08
相关资源
相似解决方案