Home » JVM Languages » Groovy » Groovy String Example

About Huseyin Babal

Huseyin Babal
Huseyin Babal has deep experience in Full Stack Development since 2007. He is mainly developing applications with JAVA, Spring, PHP, NodeJS, AngularJS. He is also interested in DevOps Engineering since 2013 and using AWS, Heroku for Cloud deployment and playing with Docker and Consul for implementing infinite scalable systems. He likes to share his experience in public conferences and perform advanced workshops about Full Stack Development and Devops. He is the author of NodeJS in Action course in Udemy.

Groovy String Example

1. Introduction

String related manipulations have been always important in almost all programming languages. If you are using Groovy, you will do String manipulation in an easy way. In other words, it is very easy to split, add, manipulate, initialize, escape Strings in Groovy. In this tutorial I will show you how to use Groovy String efficiently.
 
 
 
 
 
 

2. Warmup

Let’s have a look at following examples for warming up.

GroovyStringBasic.groovy

package main.javacodegeeks.groovy

class GroovyStringBasic {

	static main(args) {
		def name = 'John' // John
		println name
		
		println 'The quick brown fox jumps over the lazy dog'.length() // 43
		println 'Non-Blocking IO'.indexOf("o") // 1
		println 'AngularJS Service vs Factory vs Provider'.substring(32) // Provider
		println 'C# is the best'.replace('C#', 'Java') // Java is the best
		println 'I am very angry'.toUpperCase() // I AM VERY ANGRY
	}

}

As in other programming languages, Groovy is also capable of doing basic operations. On line 06 we have defined a String and then printed it on line 07 as you may guess. On line 09, we have printed the length of the given String. On line 10, we have printed the index of the first occurrence of character o which is 1. On line 11, we have applied sub string operation in order to pull string from specific starting point that we desired. Replacement is one of the basic operations in Strings. We have replaced C# with Java on line 12. And finally, we have changed the case of the string letters by using toUpperCase()

3. Concatenation vs GString

In order to concatenate string in Groovy you can use following example.

GroovyStringConcat.groovy

package main.javacodegeeks.groovy

class GroovyStringConcat {

	static main(args) {
		def name = 'John'
		def surname = 'Doe'
		println 'Hello ' + name + ' ' + surname // Hello John Doe
	}

}

As you can see we have used + sign to concate two given string. There is another way to show two string in combined way. When you look at following example.

GroovyGString.groovy

package main.javacodegeeks.groovy

class GroovyGString {

	static main(args) {
		def name = 'John'
		def surname = 'Doe'
		
		println "Hello ${name} ${surname}" // Hello John Doe
		println 'Hellow ${name} ${surname}' // Hellow ${name} ${surname}
	}

}

You will see that, the expression on line 09 compiled as string, but on line 10 the string is printed as it is. The double quote " is called in Groovy as GStrings and this accepts expressions inside.

3. Operators

You can apply math operators to Groovy strings to add, multiply or subtract them. Let’s see following examples.

GroovyOperators.groovy

package main.javacodegeeks.groovy

class GroovyOperators {

	static main(args) {
		println 'I am very long sentence' - 'very long ' // I am sentence
		println 'I will ' + ' be very long sentence' // I will  be very long sentence
		println 'Ice ' * 2 + ' baby' // Ice Ice  baby
	}

}

On line 06, we have removed part of the sentence by using - operator. It is something like removing string by using sub string, or apply replace operation on a string. This is very simple operation as you see in the example. On line 07, we have concatenated the strings by using + sign. The strange one is multiplication of the stirng on line 08. When you multiply a string, that string will be self concatenated it self by multiplication factor.

4. Multiple Lined Strings

You can use triple quote “”” for the multiple lined strings like below.

GroovyMultiLinedString.groovy

package main.javacodegeeks.groovy

class GroovyMultiLinedString {

	static main(args) {
		def multiLine = """
Hi everyone, I will
write lots of things here
because I am not restricted with
one line. I am capable of 
multi lines
		"""
		println multiLine
	}

}

As you can see, we have written multi line string in triple quoted strings and it will printed as it is.

5. String Tokenize

Tokenize is used for splitting Strings by a delimiter. If you do not provide delimiter, it will be splitted by space, tab, or next line. Let’s see how it works.

GroovyTokenize.groovy

package main.javacodegeeks.groovy

class GroovyTokenize {

	static main(args) {
		def text = 'Hello World'
		println text.tokenize() // [Hello, World]
		
		def textWithComma = 'Hello,World'
		println textWithComma.tokenize(',') // [Hello, World]
		
		def textWithTab = 'Hello	World'
		println textWithTab.tokenize()
	}

}

On line 07, it was delimited by space by default and printed an array with two elements that is [Hello, World]. On line 10, we have used , as delimiter and it has also delimited to an array. And in last example, it was automatically delimited by the tab.

6. Conclusion

Groovy String is very flexible usage while you are developing application. It lets you to save lots of lines due to its practical usage. You can do lots of manipulation on Groovy Strings with power of Groovy.

Download
You can download the full source code of this example as an Eclipse project here: GroovyStringExample
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of