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:

  1. In Groovy, we don’t need to explicitly declare a main function. The script will execute from top to bottom.

  2. We use groovy.transform.Field to declare a script-wide variable p as an alias for System.out.println.

  3. 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.

  4. Some method names are slightly different:

    • HasPrefix becomes startsWith
    • HasSuffix becomes endsWith
    • Index becomes indexOf
  5. The Join operation in Groovy is a method on lists (or any collection), not on strings.

  6. String repetition in Groovy uses the * operator instead of a Repeat method.

  7. Replace operations in Groovy are split into replaceAll (which replaces all occurrences) and replaceFirst (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.