遍历字符串中的行,包括换行符 [英] Iterate over lines in a string, including the newline characters

查看:49
本文介绍了遍历字符串中的行,包括换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要遍历字符串中的行,但将换行符保留在产生的字符串的末尾.

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

str.lines(),但它返回的字符串将换行符切掉:

There is str.lines(), but the strings it returns have the newline characters chopped off:

let result: Vec<_> = "foo\nbar\n".lines().collect();
assert_eq!(result, vec!["foo", "bar"]);

这是我需要的:

assert_eq!(lines("foo\nbar\n"), vec!["foo\n", "bar\n"]);

更多测试用例:

assert!(lines("").is_empty());
assert_eq!(lines("f"), vec!["f"]);
assert_eq!(lines("foo"), vec!["foo"]);
assert_eq!(lines("foo\n"), vec!["foo\n"]);
assert_eq!(lines("foo\nbar"), vec!["foo\n", "bar"]);
assert_eq!(lines("foo\r\nbar"), vec!["foo\r\n", "bar"]);
assert_eq!(lines("foo\r\nbar\r\n"), vec!["foo\r\n", "bar\r\n"]);
assert_eq!(lines("\nfoo"), vec!["\n", "foo"]);
assert_eq!(lines("\n\n\n"), vec!["\n", "\n", "\n"]);

我有一个基本上在循环中调用 find 的解决方案,但我想知道是否有更优雅的方法.

I have a solution that basically calls find in a loop, but I'm wondering if there's something more elegant.

这类似于 拆分字符串保留分隔符,但在在这种情况下,字符作为单独的项目返回,但我想将它们保留为字符串的一部分:

This is similar to Split a string keeping the separators, but in that case, the characters are returned as separate items, but I want to keep them as part of the string:

["hello\n", "world\n"]; // This
["hello", "\n", "world", "\n"]; // Not this

推荐答案

我目前的解决方案如下:

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)
    }
}

这篇关于遍历字符串中的行,包括换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆