How do I split a string in Rust?

前端 未结 5 1114
情深已故
情深已故 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:18

    There are three simple ways:

    1. By separator:

      s.split("separator")  |  s.split('/')  |  s.split(char::is_numeric)
      
    2. By whitespace:

      s.split_whitespace()
      
    3. By newlines:

      s.lines()
      

    The result of each kind is an iterator:

    let text = "foo\r\nbar\n\nbaz\n";
    let mut lines = text.lines();
    
    assert_eq!(Some("foo"), lines.next());
    assert_eq!(Some("bar"), lines.next());
    assert_eq!(Some(""), lines.next());
    assert_eq!(Some("baz"), lines.next());
    
    assert_eq!(None, lines.next());
    

提交回复
热议问题