How to Work with Strings in Groovy

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 of experience in training, development, and consulting in a variety of technology areas including Python, Java, C, C++, XML, JavaScript, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen has a degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.