Learn/Scala/8. Strings and a small project
Lesson 8 of 8
Sign in

Scala, lesson 8

Strings and a small project

Text is everywhere: names, commands, file lines. A Scala String is immutable, so every operation below returns a new string and leaves the original alone.

Everyday string methods

Splitting and joining

split breaks a string into an Array of pieces. Its argument is a regular expression, so "\\s+" means "one or more whitespace characters". mkString goes the other way:

Strings are collections of characters

Because a String behaves like a sequence of Char, all the collection methods from the last lesson work on it. Char has handy tests such as , , and :

2 exercises to try what you just read.

Exercise 1

Palindrome checker

Press Ctrl Enter or Check to test your code.

Exercise 2

Class report

Press Ctrl Enter or Check to test your code.

isLetter
isDigit
isWhitespace
isUpper

Comparing strings

== compares the characters, so "abc" == "abc" is true. For a case-insensitive check, use a.equalsIgnoreCase(b). < and > compare alphabetically (by character codes, so all uppercase letters come before lowercase ones).

Formatting

The f interpolator pads and aligns as well as rounding: %-8s left-aligns a string in 8 columns, %5d right-aligns a number in 5, and %.1f keeps one decimal.

Putting it together

The last exercise is a small project that uses everything from this course: reading input, converting text, decisions, a loop, a helper method, a collection and formatted output. A good way to approach a program like this:

  1. Read and parse the input into a collection.
  2. Write small methods for each rule (here: turning a score into a grade).
  3. Loop over the collection to print the details.
  4. Use collection methods (map, sum, maxBy) for the summary.

maxBy returns the element with the largest value of some property. On a tie it keeps the first one it found:

_._2 means "the second part of the tuple". You can also take a tuple apart with val (name, score) = pair.

Further reading

  • Scala 3 Book: Strings
  • Scala 3 Book: String Interpolation
  • Scala API: StringOps

Read one line of text and print four lines:

For the palindrome test, ignore case and ignore every character that is not a letter. So Never odd or even counts as a palindrome.

Sample input:

Sample output:

Time for a small project. The first input line is the number of students (at least 1). Each following line has a student's name and a whole-number score from 0 to 100, separated by a space.

Grades: 90 or more is A, 80 or more is B, 70 or more is C, 60 or more is D, anything lower is F.

Print one line per student in input order, <name>: <score> (<grade>). Then print the average score with one decimal place, and the name of the top student. If several students share the top score, print the one who appears first.

Sample input:

Sample output:

val s = "Hello, Scala"
s.length               // 12
s.toUpperCase          // HELLO, SCALA
s.toLowerCase          // hello, scala
s(0)                   // 'H'  (a Char; indexes start at 0)
s.substring(7)         // Scala
s.substring(0, 5)      // Hello  (end index not included)
s.take(5)              // Hello
s.drop(7)              // Scala
s.reverse              // alacS ,olleH
s.contains("Sca")      // true
s.startsWith("He")     // true
s.indexOf("l")         // 2   (-1 when not found)
s.replace("Hello", "Hi")  // Hi, Scala
"  padded  ".trim      // padded
"ab" * 3               // ababab
val words = "red  green blue".split("\\s+")   // Array(red, green, blue)
words.mkString(", ")                          // red, green, blue
"R2-D2".filter(_.isDigit)         // 22
"R2-D2".count(_.isLetter)         // 2
"hello world".split(" ").map(_.capitalize).mkString(" ")   // Hello World
val name = "Ada"
val score = 95
println(f"$name%-8s|$score%5d|")   // Ada     |   95|
val players = List(("Ann", 7), ("Bo", 9), ("Cy", 9))
players.maxBy(_._2)   // ("Bo", 9)
Upper: <the line in uppercase>
Reversed: <the line reversed>
Length: <number of characters in the line>
Palindrome: <yes or no>
Never odd or even
Upper: NEVER ODD OR EVEN
Reversed: neve ro ddo reveN
Length: 17
Palindrome: yes
3
Ada 95
Ben 72
Cleo 88
Ada: 95 (A)
Ben: 72 (C)
Cleo: 88 (B)
Average: 85.0
Top: Ada