如何从字符串中删除新行字符?

时间:2016-10-25 08:28:26

标签: elixir

我想删除所有换行符号:

aaa = """
fdsfds fdsfds
  fdsfdsfds
fdsfdsfds
""" |> String.strip("\r\n")

我得到了:

argument error

这有什么问题?

2 个答案:

答案 0 :(得分:9)

  

这有什么问题?

String.strip仅支持删除一个字符。当Elixir尝试将"\r\n"转换为单个字符(source)时,会抛出该错误:

iex(1)> s = "\r\n"
"\r\n"
iex(2)> <<s::utf8>>
** (ArgumentError) argument error

此外,String.strip已被弃用,而String.trim支持将字符串作为第二个参数,但该函数只会从开头删除确切的序列\r\n。字符串的结尾:

iex(1)> aaa = """
...(1)> fdsfds fdsfds
...(1)>   fdsfdsfds
...(1)> fdsfdsfds
...(1)> """
"fdsfds fdsfds\n  fdsfdsfds\nfdsfdsfds\n"
iex(2)> String.trim(aaa, "\r\n")
"fdsfds fdsfds\n  fdsfdsfds\nfdsfdsfds\n"
iex(3)> String.trim(aaa, "\r\n") == aaa
true

我怀疑你想要的是什么,因为你说“我想删除所有新行的符号”。要删除所有\r\n,您可以使用String.replace两次:

iex(4)> aaa |> String.replace("\r", "") |> String.replace("\n", "")
"fdsfds fdsfds  fdsfdsfdsfdsfdsfds"

答案 1 :(得分:0)

转义换行符

"""
fdsfds fdsfds \
  fdsfdsfds \
fdsfdsfds
"""