Scala中的换行符 [英] New line character in Scala

查看:1837
本文介绍了Scala中的换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala中是否有换行符的简写形式?在Java(在Windows上)中,我通常只使用"\ n",但这似乎在Scala中不起作用-尤其是

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)

输出

abcd
efg

在Eclipse中,

efgd

通过命令行

(原文如此)和

(sic) from the command line, and

abcdefg

来自REPL(大成功!)

from the REPL (GREAT SUCCESS!)

String.format("%n")有用,但是还有什么更短的吗?

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

推荐答案

您的Eclipse将换行标记设置为标准Windows \ r \ n,因此您获得了"abcd \ r \ nefg".正则表达式将其转换为"abcd \ refg",Eclipse控制台对\ r的处理方式与Windows Shell的处理方式略有不同. REPL只是使用\ n作为新的行标记,因此可以正常工作.

Your Eclipse making the newline marker the standard Windows \r\n, so you've got "abcd\r\nefg". The regex is turning it into "abcd\refg" and Eclipse console is treaing the \r slightly differently from how the windows shell does. The REPL is just using \n as the new line marker so it works as expected.

解决方案1:将Eclipse更改为仅使用\ n换行符.

Solution 1: change Eclipse to just use \n newlines.

解决方案2:当您需要控制换行符,使用单引号和显式\ n字符时,请不要使用三引号引起来的字符串.

Solution 2: don't use triple quoted strings when you need to control newlines, use single quotes and explicit \n characters.

解决方案3:使用更复杂的正则表达式替换\ r \ n,\ n或\ r

Solution 3: use a more sophisticated regex to replace \r\n, \n, or \r

这篇关于Scala中的换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆