String Functions in Groovy
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:
This demonstrates how Groovy provides similar string manipulation capabilities to other languages, with its own idiomatic approach.