Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the new line characters from a string?

Tags:

elixir

I want to remove all the newline symbols:

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

And I get:

argument error

What's wrong with this?

like image 304
Meji Avatar asked Oct 25 '16 08:10

Meji


People also ask

How do I remove all newline characters from a string?

That’s something we do with C#’s TrimEnd () method. One version of that method accepts specific characters to remove. When we specify the carriage return character ( ) and line feed character ( ), the method removes any and all newline from the string’s tail end. For instance:

How to strip the newlines from the start of a string?

Its value is a multi-line string with two words. Let’s strip the newlines from the start of this string. To do so we call the TrimStart () string method on the variable. Between the method’s parentheses we specify two characters: the carriage return character ( ) and line feed character ( ).

How do I trim the leading part of a string?

To trim a string’s leading part we use C#’s TrimStart () method. With one version of that method we can specify which characters to remove. When we choose the carriage return character ( ) and line feed character ( ), the method removes all newlines from the string’s start.

How to clear text strings of text in C?

One option that cleans strings of text is to remove newlines. Let’s see how we do that in the C# programming language. Newlines are special whitespace characters that signals the end of a line (Wikipedia, 2019).


2 Answers

Escape the newlines

"""
fdsfds fdsfds \
  fdsfdsfds \
fdsfdsfds
"""
like image 170
Ricardo Ruwer Avatar answered Oct 21 '22 19:10

Ricardo Ruwer


What's wrong with this?

String.strip only supports removing one character. That error is thrown as Elixir tries to convert "\r\n" to a single character (source):

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

Moreover, String.strip has been deprecated in favor of String.trim, which does support a string as the second argument, but that function will only remove the exact sequence \r\n from the starting and ending of the string:

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

which I doubt is what you want as you said "I want to remove all the symbol of a new line". To remove all \r and \n, you can use String.replace twice:

iex(4)> aaa |> String.replace("\r", "") |> String.replace("\n", "")
"fdsfds fdsfds  fdsfdsfdsfdsfdsfds"
like image 29
Dogbert Avatar answered Oct 21 '22 19:10

Dogbert