Skip to content
String Operations
step 1/5

Reading — step 1 of 5

Learn

~1 min readStrings, Regex, I/O

Groovy strings get a beefed-up API beyond Java's.

Three string types

  • 'literal'String, no interpolation, slightly faster
  • "interpolated"GString (or String if no expressions), interpolation with $var or ${expr}
  • '''triple''' or """triple""" — multi-line, both with/without interpolation
def name = "Ada"
def plain = 'no interpolation: $name'    // literal $name
def interp = "hello, $name!"              // hello, Ada!
def multi = '''line 1
    line 2
    line 3'''

Operations

"hello".size()           // 5 (or .length() — Groovy makes them equivalent)
"hello".toUpperCase()
"hello".reverse()
"hello".center(11, '-')   // "---hello---"
"hello".padLeft(10)       // "     hello"
"hello".padRight(10, '*')  // "hello*****"
"a,b,c".split(",")        // ["a", "b", "c"]
["a","b","c"].join(",")   // "a,b,c"
"hello world".tokenize()  // ["hello", "world"]

Substring tricks

"hello"[0]                // "h"
"hello"[1..3]             // "ell"
"hello"[-1]               // "o" (last)
"hello"[-3..-1]           // "llo"
"hello".take(2)           // "he"
"hello".drop(2)           // "llo"

Format

String.format("%-10s %5d", "hi", 42)
printf("%.2f%%\n", 99.5)

Conversion

"42".toInteger()
"42" as int
"3.14".toFloat()
Integer.parseInt("42")

StringBuilder shortcut

def sb = new StringBuilder()
[1, 2, 3].each { sb.append("$it,") }
println sb.toString()      // "1,2,3,"

Groovy's collection operators (each, collect) return strings or fresh collections — for true mutation use StringBuilder.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…