问题
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 .format
method 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