String formatting in scala

拟墨画扇 提交于 2019-12-08 09:03:20

问题


I am looking for a string format solution in Scala. I have the below string:

str =  {"card_id" : %s,"cust_id": %s,"card_info": {"card_type" : "%s","credit_limit": %s},"card_dates" : [{"date":"%s" },{"date":"%s" }]} 

And here I want to replace "%S" with string value. Is there any function in Scala so that I can apply that function and get the proper result?

I have tried string.format("%s", str, arrayofvalue) but it's not giving the proper result.


回答1:


In scala you can do this

val i = 123
val s = " a string"

val str = s"Here's$s $i" // result: Here's a string 123



回答2:


You could simply use:

val str = """{"card_id" : %s,"cust_id": %s,"card_info": {"card_type" : "%s","credit_limit": %s},"card_dates" : [{"date":"%s" },{"date":"%s" }]}"""
str.format(arrayofvalue:_*)

Note that I have use """ for using double quote in str as literal.




回答3:


Scala provides several ways of string interpolation.

s"" - String Interpolator

s"$var text ${var.func}"

see http://docs.scala-lang.org/overviews/core/string-interpolation.html

String.format

Scala also supports the .formatmethod on strings

scala> "%s - %d".format("test", 9)
res5: String = test - 9

http://alvinalexander.com/scala/scala-string-formatting-java-string-format-method

Using a JSON lib

As you are creating JSON here you should use on of the many JSON libraries like

  • JSON4s http://json4s.org/
  • Spray JSON https://github.com/spray/spray-json
  • Play JSON

This will give you much more safety for this task than string interpolation.



来源:https://stackoverflow.com/questions/37002294/string-formatting-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!