【发布时间】:2016-11-07 00:05:31
【问题描述】:
我需要遍历字符串中的行,但将换行符保留在产生的字符串的末尾。
有str.lines(),但它返回的字符串中的换行符被剪掉了:
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 的解决方案,但我想知道是否有更优雅的东西。
这类似于Split a string keeping the separators,但在这种情况下,字符作为单独的项目返回,但我想将它们保留为字符串的一部分:
["hello\n", "world\n"]; // This
["hello", "\n", "world", "\n"]; // Not this
【问题讨论】: