Skip to content
Groovy 15 – STRING

A String is a text. Any text is a String.

String is not just a simple data type; it is actually a class. This means it can be manipulated using specific methods defined in this class. Every string created is an object of the String class.

Defining a String

        def myString = "This is a String"
        

or

        String myString = "This is my String"
        

You can always spot a string as it is between double quotes " " or single quotes ' '.

String Operations

1 - Concatenation

Concatenation is done using the + sign:

        def x = "This is " + "a " + "String"
        println(x)
        

Output: This is a String

        def x = "This "
        def y = "is "
        def z = "a string"
        println(x + y + z)
        

Output: This is a string

2 - Escape Sequences

Escape sequences are special characters that have specific functions in strings. One of the most used is the newline \n:

        def myString = "This is" + "\n" + "new line"
        println(myString)
        

Output:

This is
new line

3 - Useful Methods of the String Class

a) Getting the length of a string
        def myString = "This is a String"
        def x = myString.length()
        println(x)
        

Output: 16

b) Extracting a substring between two delimiters
        def myString = ""
        def result = myString.substring(myString.indexOf("<") + 1, myString.indexOf(">"))
        println(result)
        

Output: My Text Here

c) Removing brackets when returning an array
        def myArray = [1, 2, 3, 4]
        def string_val = myArray.toString().substringAfter('[').substringBefore(']')
        println(string_val)
        

Output: 1, 2, 3, 4

d) Replacing a string with another using replaceAll()
        def myString = ""
        def newString = myString.replaceAll('<', '**')
        println(newString)
        

Output: **My Test Here>

Note: Strings are immutable, which means you can never change the object itself. Once you create a string, it can never be changed. Each time you change something in a string or extract a substring, a new string object is created.