Groovy, lesson 8
Groovy strings are Java strings with extra conveniences: indexing with brackets, ranges for slicing, GString templates and many helper methods added by Groovy's development kit.
Indexing with a range gives a slice; a negative index counts from the end, so -1 is the last
character. Strings are immutable: toUpperCase() returns a new string and leaves s alone.
capitalize() upper-cases just the first letter: "ada".capitalize() is "Ada".
split cuts a string using a regular expression. Groovy's slashy strings, /.../, are handy
for patterns because backslashes need no escaping. means "one or more whitespace
characters":
2 exercises to try what you just read.
/\s+/tokenize() splits on whitespace and never produces empty pieces, even when the string starts
with spaces. split on a string that starts with a space gives an empty first piece, so trim()
first when you use it.
GStrings are the easiest way to build text. For aligned columns, String.format (or the
formatted method) pads values:
%-8s pads a string to 8 characters on the right; %5d pads a number to 5 on the left.
The last exercise is a receipt printer that uses nearly every lesson: reading input, converting text to numbers, a method, a loop, a list and formatted output. Plan before you type:
Groovy's multiple assignment helps with step 2: def (name, qty, price) = line.tokenize()
puts the three pieces into three variables in one go.
Read a full name on one line. Print the initials in upper case, each followed by a dot. The name may be in any case and may contain extra spaces between words.
Sample input:
Sample output:
Each input line describes one item: a name, a quantity and a unit price, separated by single
spaces. Prices are whole numbers. For every item print name: quantity x price = subtotal, then
finish with the total number of items and the total cost. Ignore empty lines.
Sample input:
Sample output:
def s = "Hello, Groovy"
println s.size() // 13
println s[0] // H
println s[7..-1] // Groovy (from index 7 to the last character)
println s[0..<5] // Hello (indexes 0 to 4)
println s.toUpperCase() // HELLO, GROOVY
println " padded ".trim() // padded
println s.reverse() // yvoorG ,olleHdef words = "red green blue".split(/\s+/) // [red, green, blue]
println words.join(", ") // red, green, blue
println "a b c".tokenize() // [a, b, c]url.startsWith("http")
file.endsWith(".groovy")
"banana".contains("nan") // true
"banana".indexOf("n") // 2 (-1 if not found)
"banana".count("a") // 3
"".isEmpty() // truedef item = "apples"
def qty = 12
println "${item}: ${qty}" // apples: 12
println String.format("%-8s|%5d", item, qty) // apples | 12
println "%.2f".formatted(3.5) // 3.50grace brewster hopperG.B.H.apple 3 2
bread 1 4
cheese 2 7apple: 3 x 2 = 6
bread: 1 x 4 = 4
cheese: 2 x 7 = 14
Items: 6
Total: 24