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

bfrts1fy  于 8个月前  发布在  其他
关注(0)|答案(3)|浏览(144)

如何在Dart中删除字符串中的换行符?
例如,我想转换:

"hello\nworld"

字符串

"hello world"

lsmepo6l

lsmepo6l1#

可以使用replaceAll(pattern,replacement):

main() {
  var multiline = "hello\nworld";
  var singleline = multiline.replaceAll("\n", " ");
  print(singleline);
}

字符串

hof1towb

hof1towb2#

@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")

yjghlzjz

yjghlzjz3#

尝试使用

multieLine.replaceAll(RegExp(r"\\n"), "");

字符串
当试图删除任何与“”use“\”相关的内容时,

相关问题