Kotlin, lesson 8
Text is everywhere in programs: names, commands, file lines, messages. A Kotlin String is a
sequence of characters, and it comes with a large toolbox of functions.
A string can't be modified after it is created. Functions like uppercase() or trim() don't
change the original; they return a new string. Remember to use the result:
You can loop over a string's characters directly with for (ch in word). Each ch is a
Char, which has its own helpers such as isDigit(), isLetter() and .
2 exercises to try what you just read.
uppercaseChar()| Call | Result |
|---|---|
" hi ".trim() | "hi" |
"Hi".lowercase() | "hi" |
"ada".replaceFirstChar { it.uppercase() } | "Ada" |
"a-b-c".replace("-", "+") | "a+b+c" |
"stressed".reversed() | "desserts" |
"ab".repeat(3) | "ababab" |
"7".padStart(3, '0') | "007" |
"red green".split(" ") | ["red", "green"] |
listOf("a", "b").joinToString("/") | "a/b" |
padStart and padEnd are handy for lining up output: they add characters until the string
reaches the length you ask for, and leave longer strings alone.
String templates ("$name has ${items.size} items") cover most needs. When you build a long
string piece by piece in a loop, buildString { append(...) } is efficient and tidy:
For the project you'll read lines until there are none left. readlnOrNull() returns null
at the end of input. The Elvis operator ?: says "if the left side is null, use the right
side instead", and the right side may even be break:
After this line, Kotlin knows line is a real String, not null, so you can use it freely.
The final exercise is a small project that uses something from every lesson: printing,
variables, input and arithmetic, decisions, loops, a helper function, a list and string
functions. Plan it before you type: what do you read, what do you keep track of, what do you
print at the end? Writing a small function for the fiddly part (formatting money) keeps main
easy to read.
Read a full name: two or more words separated by single spaces (there may be extra spaces at the start or end of the line). Print two lines:
Initials: followed by the first letter of each word in uppercase, each followed by a dot.Username: followed by the first letter of the first word and the whole last word, all in
lowercase.Sample input:
Sample output:
Build a receipt printer. Each input line describes one item: a name in lowercase, a quantity
and a unit price in cents, separated by single spaces, like apple 3 50. Read lines until
the input ends (skip any blank line).
For each item, print the name with its first letter capitalized, x and the quantity, and the
line cost in dollars with exactly two decimals. Then print the total number of items (the sum
of the quantities) and the total cost.
Write a helper function formatCents(cents: Int): String that turns 375 into "3.75" and
5 into "0.05". Use whole-number maths (/ and %) and padStart, not Double, so no
rounding errors creep in.
Sample input:
Sample output:
If there are no items at all, print Items: 0 and Total: 0.00.
val shout = "hello"
shout.uppercase() // result thrown away, shout is still "hello"
val loud = shout.uppercase() // "HELLO"val word = "Kotlin"
println(word.length) // 6
println(word[0]) // K (a Char)
println(word.last()) // n
println(word.substring(1, 4)) // otl (from index 1 up to, not including, 4)
println(word.contains("lin")) // true
println(word.startsWith("Ko")) // true
println(word.indexOf('t')) // 2val stars = buildString {
for (i in 1..3) append("*")
}
println(stars) // ***while (true) {
val line = readlnOrNull() ?: break // stop at the end of input
println(line.uppercase())
}Grace Brewster HopperInitials: G.B.H.
Username: ghopperapple 3 50
bread 1 225Apple x3 1.50
Bread x1 2.25
Items: 4
Total: 3.75