1

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.

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.