Iterate over lines in a string, including the newline characters

前端 未结 1 1418
野性不改
野性不改 2021-01-18 22:04

I need to iterate over lines in a string, but keep the newlines at the end in the strings that are yielded.

There is str.lines(), but the strings it returns have the

相关标签:
1条回答
  • The solution I currently have looks like this:

    /// Iterator yielding every line in a string. The line includes newline character(s).
    pub struct LinesWithEndings<'a> {
        input: &'a str,
    }
    
    impl<'a> LinesWithEndings<'a> {
        pub fn from(input: &'a str) -> LinesWithEndings<'a> {
            LinesWithEndings {
                input: input,
            }
        }
    }
    
    impl<'a> Iterator for LinesWithEndings<'a> {
        type Item = &'a str;
    
        #[inline]
        fn next(&mut self) -> Option<&'a str> {
            if self.input.is_empty() {
                return None;
            }
            let split = self.input.find('\n').map(|i| i + 1).unwrap_or(self.input.len());
            let (line, rest) = self.input.split_at(split);
            self.input = rest;
            Some(line)
        }
    }
    
    0 讨论(0)
提交回复
热议问题