Reputation: 83
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.
Upvotes: 1
Views: 2911
Reputation: 10884
Scala provides several ways of string interpolation.
s"$var text ${var.func}"
see http://docs.scala-lang.org/overviews/core/string-interpolation.html
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
As you are creating JSON
here you should use on of the many JSON
libraries like
This will give you much more safety for this task than string interpolation.
Upvotes: 0
Reputation: 4256
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.
Upvotes: 2
Reputation: 6363
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
Upvotes: 1