Amit Kumar
Amit Kumar

Reputation: 83

String formatting in scala

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

Answers (3)

Andreas Neumann
Andreas Neumann

Reputation: 10884

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.

Upvotes: 0

justAbit
justAbit

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

Simon
Simon

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

Related Questions