Split a string keeping the separators

前端 未结 3 1593
既然无缘
既然无缘 2020-12-06 17:40

Is there a trivial way to split a string keeping the separators? Instead of this:

let texte = \"Ten. Million. Questions. Let\'s celebrate all we\'ve done tog         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 17:45

    The unstable function str::split_inclusive returns an iterator keeping the delimiters as part of the matched strings, and may be useful in certain cases:

    #![feature(split_inclusive)]
    
    #[test]
    fn split_with_delimiter() {
        let items: Vec<_> = "alpha,beta;gamma"
            .split_inclusive(&[',', ';'][..])
            .collect();
        assert_eq!(&items, &["alpha,", "beta;", "gamma"]);
    }
    
    #[test]
    fn split_with_delimiter_allows_consecutive_delimiters() {
        let items: Vec<_> = ",;".split_inclusive(&[',', ';'][..]).collect();
        assert_eq!(&items, &[",", ";"]);
    }
    

提交回复
热议问题