Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New line character in Scala

Tags:

Is there a shorthand for a new line character in Scala? In Java (on Windows) I usually just use "\n", but that doesn't seem to work in Scala - specifically

val s = """abcd efg""" val s2 = s.replace("\n", "") println(s2) 

outputs

abcd efg 

in Eclipse,

efgd 

(sic) from the command line, and

abcdefg 

from the REPL (GREAT SUCCESS!)

String.format("%n") works, but is there anything shorter?

like image 917
Luigi Plinge Avatar asked May 31 '11 21:05

Luigi Plinge


People also ask

What is the character for new line?

LF (character : \n, Unicode : U+000A, ASCII : 10, hex : 0x0a): This is simply the '\n' character which we all know from our early programming days. This character is commonly known as the 'Line Feed' or 'Newline Character'.

How do I print a line in Scala?

Method # 1: Using the “println” Command The “println” command in the Scala programming language is used to print a line while introducing a new line at the end. In this way, if you want to print more than one line, each of them will be printed on a separate line.

What is escape character in Scala?

An escape value is a backslash with a character that will escape that character to execute a certain functionality. We can use these in character and string literals. We have the following escape values in Scala: Escape Sequences. Unicode.

What is stripMargin in Scala?

stripMargin ( '#' ) All of these approaches yield the same result, a multiline string with each line of the string left justified: Four score and seven years ago. This results in a true multiline string, with a hidden \n character after the word “and” in the first line.


1 Answers

A platform-specific line separator is returned by

sys.props("line.separator") 

This will give you either "\n" or "\r\n", depending on your platform. You can wrap that in a val as terse as you please, but of course you can't embed it in a string literal.

If you're reading text that's not following the rules for your platform, this obviously won't help.

References:

  • scala.sys package scaladoc (for sys.props)
  • java.lang.System.getProperties javadoc (for "line.separator")
like image 158
Ed Staub Avatar answered Sep 28 '22 04:09

Ed Staub