Home » JVM Languages » Groovy » Groovy Substring 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 Substring Example

Sometimes, the provided text may not be suitable for our needs. Because of this, we use string manipulation functions to convert it to desired format or extract specific part of it. You can hear this operation as substring operation in software development world. In this tutorial, I will show you how to apply substring operations on a given string. In Groovy, you can use several ways to extract specific part of a given string. Let’s have a look at alternative ways to do some substring operations on strings

1. Substring Usage

Let say that you are doing some operations on logs generated by your applications. You have a log entry like Exception on saving user with username: johntheripper. Assume that your job here is the extract username from the log entry. You can see following example.

 
GroovySubstring.groovy

package main.java.javacodegeeks.groovysubstring

class GroovySubstring {

	static main(args) {
		def log = "Exception on saving user with username:johntheripper"
		def username = log.substring(log.lastIndexOf(":") + 1, log.length())
		println username // johntheripper
		
		def usernameWithoutEndIndex = log.substring(log.lastIndexOf(":") + 1)
		println usernameWithoutEndIndex // johntheripper
	}

}

In this example, we used String.substring(int beginIndex, int endIndex). In this function, we specified start and end index to extract portion of text with bounded with startIndex and endIndex. log.lastIndexOf(":") gives us the index of the character : and log.length() for the end index of the log entry. Here is the character length is endIndex – startIndex, and that is why we used log.length() instead of log.length() - 1. If you use log.length() - 1 as endIndex, it will give you johntherippe. We will frequently use indexes on substring operations, and this indexes is zero based indexes. If you do not provide endIndex, it will extract string till the end of text.

2. Subsequence Usage

Actually, subsequence works as substring, but there is a small difference between them. Subsequence returns char sequence while substring returns string. Let’s see how it works.

GroovySubsequence.groovy

package main.java.javacodegeeks.groovysubstring

class GroovySubsequence {

	static main(args) {
		def log = "Exception on saving user with username:johntheripper"
		def username = log.subSequence(log.lastIndexOf(":") + 1, log.length())
		println username // johntheripper
	}

}

CharSequence is an interface while String is a class. Also, every String is a CharSequence.

3. Groovy Style Substring

we saw the Java style substring until this point. We will see some Groovy based substring operations in this section. For a fresh start, you can see following example.

GroovyStyleSubstring.groovy

package main.java.javacodegeeks.groovysubstring

class GroovyStyleSubstring {

	static main(args) {
		def text1 = "My last character will be removed soon"
		println text1[0..-2] // My last character will be removed soo
		
		def text2 = "My first word will be removed soon";
		println text2[3..-1] // first word will be removed soon
		
		def text3 = "noos em daer lliw uoy ,tneitap eB"
		println text3[-1..0] // Be patient, you will read me soon	
	}

}

As you can see, Groovy style substring is more readable and easy to understand. You can simply use square bracket ([]) for define boundaries. .. between start and end index is states for interval. For example, 0..5 means extract characters from index 0 to index 5 as string. On 13th line, you can see startIndex is negative number. This means, the index starts from the end of string. endIndex is a positive number and this will extract the string in reverse order.

4. getAt Substring

You can use getAt(IntRange range) for extract a string portion from a given text. You can simply do that by providing the range of the portion like below.

GroovyGetAt.groovy

package main.java.javacodegeeks.groovysubstring

class GroovyGetAt {

	static main(args) {
		def text1 = "crazy fox jumps over lazy dog"
		println text1.getAt(0..(text1.length() - 5)) // crazy fox jumps over lazy  
		
		def text2 = "keep calm and carry on"
		println text2.getAt(-1..5) // no yrrac dna mlac
	}

}

As you can see, you can use getAt by providing range of the characters to be extracted. Also, you can provide negative starting index to start extracting in reverse order.

5. Subtract Notation

In Groovy, you can subtract string by using subs sign like in the Math science. You can have a look at following example for understand it more.

GroovySubtractString.groovy

package main.java.javacodegeeks.groovysubstring

class GroovySubtractString {

	static main(args) {
		def text1 = "Sorry, I need to separate from you"
		println text1 - " you" // Sorry, I need to separate from
		
		def text2 = "Minus string usage"
		println text2.minus(" usage") // Minus string
	}

}

You can remove any string from the text by using the - sign. Alternatively, you can use minus function to subtract desired string from given text.

6. Conclusion

String operations are very easy stuff in Groovy. You can apply substring operation on strings by using some function comes from Java (substring, and subSequence), and also you can use Groovy like notation ([n..m], minus, or getAt). All you need to do is provide a starting and ending index for boundaries.

Download
You can download the full source code of the project here: GroovySubstringExample
(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