Overview
This guide details the two main ways to combine Strings, as well as the most commonly used String methods and what they are used for.
Click on the String method links listed below to jump to that section.
Combining Strings
There are two primary ways to combine Strings in Groovy: Concatenation and Interpolation.
Concatenation
Concatenation using the + operator is the simplest option for combining only String variables. However, in situations involving static text and multiple variables, it can be difficult to read. See the examples below:
//Combining variables only
String abc = 'abc' as String
String 123 = '123' as String
String newString = abc+123 as String
//Output
//'abc123'
//Combining variables and static text
String firstName = 'Scott' as String
String lastName = 'Carpenter' as String
String greeting = 'Hello my name is ' + firstName + ' ' + lastName as String
//Output
// 'Hello my name is Scott Carpenter'
Interpolation
String interpolation allows us to insert variables using ${variableName}
directly in a String without requiring the + operator. This is helpful when creating custom logger messages that have static text and variables dynamically mixed in.
👀 Note: when using String interpolation, double quotes ( " ) MUST be used.
See the examples below:
//Combining variables and static
String firstName = 'Scott' as String
String lastName = 'Carpenter' as String
String greeting = "Hello my name is ${firstName} ${lastName}" as String
//Output
//'Hello my name is Scott Carpenter'
Common String Methods
-
Returns the length of a Stringlength()
String helloWorld = 'Hello World' as String
helloWorld.length()
//Output
//11
-
reverses the Stringreverse()
String helloWorld = 'Hello World' as String
String reversed = helloWorld.reverse() as String
//Output
//dlroW olleH
-
Creates a list using the provided expression. Literals and regular expressions are accepted.split()
String helloWorld = 'Hello World' as String
//Splitting on spaces
List spaceSplit = helloWorld.split(' ') as List
//Output
//[Hello, World]
//Splitting on the letter L
List lSplit = helloWorld.split('l') as List
//Output
//[He, , o Wor, d]
👀 Note that as seen in the example of splitting on the letter L shown above that the splitting character is removed when creating the resulting array.
-
Converts the provided String to upper case characters. This can be helpful when normalizing two Strings before comparing them.toUpperCase()
String helloWorld = 'Hello World' as String
helloWorld.toUpperCase()
//Output
//HELLO WORLD
-
Converts the provided string to lower case characters. This can be helpful when normalizing two Strings before comparing them.toLowerCase()
String helloWorld = 'Hello World' as String
helloWorld.toLowerCase()
//Output
//hello world
Related Articles:
Comments
0 comments
Please sign in to leave a comment.