2017-10-16 53 views
-1

我正在练习从https://www.scala-exercises.org/std_lib/formatting斯卡拉字符串格式化演习错误:没有编制

对于以下问题,男答案似乎不正确,但我不知道为什么。

val c = 'a' //unicode for a 
val d = '\141' //octal for a 
val e = '\"' 
val f = '\\' 

"%c".format(c) should be("a") //my answers 
"%c".format(d) should be("a") 
"%c".format(e) should be(") 
"%c".format(f) should be(\) 
+1

最好的建议:1. https://github.com/scala-exercises/exercises-stdlib克隆它2.安装/运行SBT – Pavel

回答

1

你的答案应该用引号括起来

"%c".format(e) should be("\"") 
"%c".format(f) should be("\\") 

,因为除非是用引号括起来

0

你的最后两行是无效的,Scala代码和不能被编译,将不能识别字符串:

// These are wrong 
"%c".format(e) should be(") 
"%c".format(f) should be(\) 

be()函数需要传递一个字符串,并且这两个调用都不会传递一个字符串。字符串需要以双引号开头和结尾(有一些例外)。

// In this case you started a String with a double-quote, but you are never 
// closing the string with a second double-quote 
"%c".format(e) should be(") 

// In this case you are missing both double-quotes 
"%c".format(f) should be(\) 

在这种情况下,代码应该是:

"%c".format(e) should be("\"") 
"%c".format(f) should be("\\") 

如果你想在一个字符串字面处理的字符,你需要“突围”它用反斜杠。所以,如果你想从字面上显示的双引号,需要用反斜线前缀是:

\" 

而作为一个字符串:

"\"" 

相若方式反斜杠:

\\ 

作为一个字符串:

"\\" 

使用IDE可以更容易地看到。使用IntelliJ字符串是绿色的,但特殊的非文字字符以橙色突出显示。

enter image description here