26

如何从 Dart 中的字符串中删除换行符?

例如,我想转换:

"hello\nworld"

"hello world"
4

2 回答 2

48

您可以使用replaceAll(模式,替换):

main() {
  var multiline = "hello\nworld";
  var singleline = multiline.replaceAll("\n", " ");
  print(singleline);
}
于 2012-06-15T14:54:51.670 回答
0

@SethLadd的答案是正确的,但在一个非常基本的例子中。

在多行输入的情况下,文本如下:

Hello, world!
{\n}
I like things:
- cats
- dogs
{\n}
I like cats, alot
{\n}
{\n}
and more cats
{\n}
{\n}
{\n}
. (ignore this dot)

在上述情况下,您的字符串表示如下:

Hello, world!\n\nI like things:\n- cats\n- dogs\n\nI like cats, alot\n\n\nand more cats\n\n\n\n

使用@SethLadd的解决方案,我将得到:

Hello, world!I like things:- cats- dogsI like cats, alotand more cats

这当然不是预期的结果。我建议使用常用的正则表达式方法来解决问题。

调用.trim()将删除最后 4 个\n(以及任何前面的\n)。

如果愿意,您可以将新行限制为单个开放行,例如

text.trim().replaceAll(RegExp(r'(\n){3,}'), "\n\n")
于 2021-07-22T17:12:10.250 回答