Formatting strings

Download Report

Transcript Formatting strings

String Formatting
Preparing strings for output
Printing

println(arg) prints its one argument on a line

println can be used to print any single value, but it doesn’t work well
with arrays or user-defined data types

scala> println(List(1, 2, 3))
List(1, 2, 3)
scala> println(Array(1, 2, 3))
[I@79916512



When printing a user-defined type, println will first look to see if you
have written a toString method that it can use
You can use println without an argument to get a blank line
print(arg) works like println, but doesn’t go to the next
line

scala> print("abc"); print("xyz")
abcxyz
2
Concatenation


The simplest way to print several values at once is to “add”
(concatenate) them with a string, with the + operator
When a value is concatenated with a string, the value’s
toString method is called


scala> println("Array is " + Array(1, 2, 3) +
", List is " + List(1, 2, 3))
Array is [I@3fd87157, List is List(1, 2, 3)
When you study classes, you will learn how to write your own
toString methods
3
Interpolation

You can insert (interpolate) the value of simple
variables into strings by doing two things:




Prefix the string with an s
Put a $ before the variable name
Example: s"Your score is $score"
You can also interpolate the value of expressions by
enclosing them in curly braces after the $

Example: s"Twice $x is ${2 * x}"
4
Formatting I

Sometimes you want more precise control over the way numbers
and dates are printed

Default:
scala> println(7 * 0.1)
0.7000000000000001
scala> println(new java.util.Date)
Sat Jul 20 12:59:33 PDT 2013

Formatted:
scala> println("Seven tenths is %5.3f".format(7 * 0.1))
Seven tenths is 0.700
scala> println("Today's date is %tD".format(new
java.util.Date))
Today's date is 07/20/13
5
Formatting

The syntax is: string.format(value, …, value)


Here are examples of the most common format specifiers







The number and types of values must agree with the format specifiers
%12d format an integer right-justified in a field of width 12
%-8d format an integer left-justified in a field of width 8
%5.3f format a floating point number right-justified in a field of width
5, with 3 digits after the decimal point
%12.3e like %12.3f, but using scientific (E) notation
%7b format a boolean right-justified in a field of width 7
%10s format a string right-justified in a field of width 10
If a field width is too small, will be ignored

Irregular spacing is better than printing the wrong number!
6
printf



printf(string, value, …, value)
is shorthand for
print(string.format(value, …, value))
Note that this is a shorter way to call print, not
println
To do the equivalent of a println, put a \n as the
last character in the string
7
The End
8