Home »
Scala
Formatting Strings in Scala
By IncludeHelp Last updated : October 20, 2024
Scala string formatting methods
Returning a string to the output screen that contains variables as well as constant elements of the text that are used in a string. To display the string in a representable form formatting of the string is required. In Scala, There are methods defined to format strings. The formatting of the string is done using two methods
- format()
- formatted()
Example
We have to return a string in a formatted form so that the final output would be as follows:
Alvin earns 400000
//or
Alex earns 78652
To return this output in which there are two variables personname and personsalary. So we need to add the personname first then the text that is to be printed and the personsalary variable at last.
Now let's see how we can return this input using a format and formatted methods?
Scala format() Method
The format() method in Scala is from the stringlike trait which holds methods for string operations. This method is used to format strings. It accepts parameters and places them on their specific positions.
The positions of variables are defined using ampersand (&) notations.
- &d is used to insert integer values
- &f is used for inserting floating point or double values
- &c is used for inserting characters
- &s is used for inserting strings
Syntax
var formatted_string = string_a.format(parameters)
Example 1
object MyClass {
def main(args: Array[String]) {
var output = "%s earns %d in a month!"
var employee_name = "Manju"
var employee_salary = 400000
var formatted_string = output.format(employee_name, employee_salary)
print(formatted_string)
}
}
Output
Manju earns 400000 in a month!
Example 2
object MyClass {
def main(args: Array[String]) {
var name = "Honda CBR 650"
var speed = 194
var formatted_string = "%s has a maximum speed of %d Km/h.".format(name, speed)
print(formatted_string)
}
}
Output
Honda CBR 650 has a maximum speed of 194 Km/h.
Scala formatted() method
The formatted() method works in the same way as the format() method. This method works on objects and it can be used for formatting output that contains text along with integers double values and strings.
Syntax
var formatted_string = value.formatted(unformatted_string)
Example 1
object MyClass {
def main(args: Array[String]) {
var speed = 124
var formattedstring = speed.formatted("Maximum speed of my bike is %d km/h")
print(formattedstring)
}
}
Output
Maximum speed of my bike is 124 km/h
Example 2
object MyClass {
def main(args: Array[String]) {
var bike = "Royal Enfield Thunderbird"
var formattedstring = bike.formatted("I have a %s")
print(formattedstring)
}
}
Output
I have a Royal Enfield Thunderbird