Grails Cookbook - A collection of tutorials and examples

Groovy Trim Examples

We will show code snippet examples on how to perform String trim in Groovy.

Trim Single String in Groovy

Below is an example on how to trim one String value in Groovy. This is similar to Java.
/**
 * A simple example that does a trim on a String.
 */
class Test {
	public static void main(String[] args) {
		def testString = "     A     "
		println "-" + testString.trim() + "-"
	}
}
This will output
-A-
And the spaces are removed.

Trim List of String in Groovy

Below is an example on how to trim a List of String in Groovy.
/**
 * A simple example that trims a List of String.
 */
class Test {
	public static void main(String[] args) {
		def listOfString = ["  A  ", "  B  ", "  C  "]
		for (i in 0..<listOfString.size()) {
			listOfString[i] = listOfString[i].trim()
		}
		println listOfString
	}
}

This will output

[A, B, C]

And each items are trimmed. Here is a shorter example:

/**
 * A simple example that trims a List of String.
 */
class Test {
	public static void main(String[] args) {
		def listOfString = ["  A  ", "  B  ", "  C  "]
		listOfString = listOfString*.trim()
		println listOfString
	}
}