How to Work with Strings in Groovy

  • google plus

In Brief...

Working with strings is important in any programming language because of the ubiquitous nature of string data. Name, addresses, descriptions and many more data fields are are stored as strings. Groovy gives the developer helpful methods (functions) for processing strings. We will look at several useful methods in the example below.


To work with strings in Groovy, follow these three steps.

  1. Open your text editor and type in the following lines of Groovy code:
    def fullName = "Jones/Norman"
    println "Display first character of fullName: ${fullName[0]}"
    def indexOfSlash=fullName.indexOf("/")
    println "First name is ${fullName.substring(indexOfSlash+1)}"
    println "Last name is ${fullName.substring(0,indexOfSlash)}"
    println "Lower case: ${fullName.toLowerCase()} Upper case: ${fullName.toUpperCase()}"
    We'll start by defining a string named fullName that contains a person's last name and first name. The last name is separated from the first name by a forward slash ("/"). Note that we can display the first character of the name by treating fullName as an array of characters. To determine the location of the slash, we use the indexOf function, or method. We can display the first name by using the substring function to display the characters of full name between the location of the slash plus one and the end of the string (the default ending location for substring). To display the last name, we again use substring specifying a beginning location of "0" and a substring length that is equal to the index of the slash character. Lastly, we use the appropriate methods to convert the string to lower case and upper case.
  2. Save your file as WorkWithStrings.groovy.
  3. In the command prompt, type in the command to interpret and run your script:
    Run strings script
    The program displays the results of applying the string operations documented above.

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.