How do I split a string in Rust?

前端 未结 5 1111
情深已故
情深已故 2020-11-30 19:18

From the documentation, it\'s not clear. In Java you could use the split method like so:

\"some string          


        
5条回答
  •  暖寄归人
    2020-11-30 20:10

    There is a special method split for struct String:

    fn split<'a, P>(&'a self, pat: P) -> Split<'a, P> where P: Pattern<'a>
    

    Split by char:

    let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
    assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
    

    Split by string:

    let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
    assert_eq!(v, ["lion", "tiger", "leopard"]);
    

    Split by closure:

    let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect();
    assert_eq!(v, ["abc", "def", "ghi"]);
    

提交回复
热议问题