String Methods
Prerequisites: Strings and GStrings
Groovy strings have all of Java's String methods, plus many extras
from the GDK (the Groovy Development Kit — Groovy's additions to
Java classes).
def s = 'Hello, Groovy'
println s.size() // same as length()
println s.toUpperCase()
println s.toLowerCase()
println s.contains('Groovy')
println s.startsWith('Hell')
println s.indexOf('o')
println s.replace('Hello', 'Goodbye')
println s.reverse()
println ' padded '.trim()
13
HELLO, GROOVY
hello, groovy
true
true
4
Goodbye, Groovy
yvoorG ,olleH
padded
Indexing and slicing
def word = 'Groovy'
println word[0]
println word[-1] // negative index counts from the end
println word[0..2] // a range of characters
println word[-3..-1]
println word[0..<3] // ..< excludes the end
G
y
Gro
ovy
Gro
Splitting and joining
def csv = 'red,green,,blue'
println csv.split(',') // Java: keeps the empty item
println csv.tokenize(',') // Groovy: drops empty items
println 'one two three'.split()
println(['a', 'b', 'c'].join(' | '))
[red, green, , blue]
[red, green, blue]
[one, two, three]
a | b | c
split returns an array and takes a regex; tokenize returns a list
and treats its argument as a set of separator characters.
Padding and formatting
println 'Name'.padRight(10, '.') + 'Score'.padLeft(6)
println 'Ada'.padRight(10, '.') + '42'.padLeft(6)
println 'Linus'.padRight(10, '.') + '7'.padLeft(6)
println 'Title'.center(15, '*')
println String.format('%-6s|%5.1f|', 'pi', 3.14159)
println 'groovy'.capitalize()
Name...... Score
Ada....... 42
Linus..... 7
*****Title*****
pi | 3.1|
Groovy
Checking content
println '123'.isNumber()
println '12a'.isInteger()
println ''.isEmpty()
println ' '.isBlank()
println 'abc'.every { it in 'a'..'z' }
println 'banana'.count('a')
true
false
true
true
true
3
Strings are immutable: every method returns a new string and leaves the original unchanged.
Practice
Given ' the quick brown fox ', print it trimmed, with each word
capitalized, joined by single spaces.
Show solution
def text = ' the quick brown fox '
println text.trim().tokenize(' ').collect { it.capitalize() }.join(' ')
The Quick Brown Fox