String Functions in Groovy
import groovy.transform.Field
// We alias println to a shorter name as we'll use it a lot below.
@Field static def p = System.out.&println
// Here's a sample of the string functions available in Groovy.
// Note that in Groovy, these are typically methods on the String object itself,
// rather than functions in a separate package.
p("Contains: " + "test".contains("es"))
p("Count: " + "test".count("t"))
p("StartsWith:" + "test".startsWith("te"))
p("EndsWith: " + "test".endsWith("st"))
p("IndexOf: " + "test".indexOf("e"))
p("Join: " + ["a", "b"].join("-"))
p("Repeat: " + "a" * 5)
p("Replace: " + "foo".replaceAll("o", "0"))
p("Replace: " + "foo".replaceFirst("o", "0"))
p("Split: " + "a-b-c-d-e".split("-"))
p("ToLower: " + "TEST".toLowerCase())
p("ToUpper: " + "test".toUpperCase())
This Groovy code demonstrates various string operations, similar to the original example. Here’s an explanation of the differences and similarities:
In Groovy, we don’t need to explicitly declare a
main
function. The script will execute from top to bottom.We use
groovy.transform.Field
to declare a script-wide variablep
as an alias forSystem.out.println
.Groovy’s string operations are typically methods on String objects, rather than functions in a separate package. This leads to a more object-oriented style of code.
Some method names are slightly different:
HasPrefix
becomesstartsWith
HasSuffix
becomesendsWith
Index
becomesindexOf
The
Join
operation in Groovy is a method on lists (or any collection), not on strings.String repetition in Groovy uses the
*
operator instead of aRepeat
method.Replace
operations in Groovy are split intoreplaceAll
(which replaces all occurrences) andreplaceFirst
(which replaces only the first occurrence).
To run this Groovy script, save it to a file (e.g., string_functions.groovy
) and execute it using the Groovy command:
$ groovy string_functions.groovy
Contains: true
Count: 2
StartsWith:true
EndsWith: true
IndexOf: 1
Join: a-b
Repeat: aaaaa
Replace: f00
Replace: f0o
Split: [a, b, c, d, e]
ToLower: test
ToUpper: TEST
This demonstrates how Groovy provides similar string manipulation capabilities to other languages, with its own idiomatic approach.