rust字符串的slice


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[..]
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM