Jay Taylor's notes
back to listing indexGroovy String Tutorial - Grails Cookbook
[web search]Beginners Tutorial
- • Setup Your Windows Development Environment
- • Model View Controller (MVC) Pattern
- • Playing with Groovy Language
- • Starting with Controllers
- • Basic Groovy Server Pages (GSP)
- • Layout Templates
- • Introduction to GORM
- • Display Data from the Database
- • Form Submission and Saving Data to the Database
- • Scaffolding
- • Grails Service Layer
- • Criteria API
- • HQL Queries (executeQuery and executeUpdate)
Example Applications
If you like my posts, like my Facebook page please :)
Groovy String Tutorial
May 28, 2014 Groovy, Tutorial 1 comments
In any programming language, Strings and String manipulations are very important. This tutorial will show how cool it is to work with String using Groovy!If you don't know how to setup an IDE and create a Groovy project, check out my post here and here.
Basics
Strings can either be defined using single or double quotes. The two objects below are Strings:
def firstName = 'John' def lastName = "Doe"
And since Groovy is superset of Java, you can use String methods you normally use in Java:
println 'ABCDEF'.length() // output: 6 println 'ABCDEF'.substring(1) // output: BCDEF println 'ABCDEF'.indexOf('C') // output: 2 println 'ABCDEF'.replace('CD', 'XX') // output: ABXXEF println 'ABCDEF'.toLowerCase() // output: abcdef
Concatenation is same as Java with the + sign.
def a = 'John' println "Hello " + a + " and welcome" // output: Hello John and welcome
Strings in double quote are called GStrings. A special property of it is it evaluates expressions inside it, enclosed in ${}. For example:
def firstName = 'John' def lastName = "Doe" println '${lastName}, ${firstName}' // output: ${lastName}, ${firstName} println "${lastName}, ${firstName}" // output: Doe, JohnNotice that the first line was taken literally, because it's just a normal String. The next line was evaluated because it's a GString.
Operators
Aside from + operator, - and * can be used:
println 'ABC' - 'B' // output: A println 'ABBC' - 'B' // output: ABC println 'ABBC' - 'BB' // output: AC println 'ABC' * 2 // output: ABCABC println 'ABC' * 3 // output: ABCABCABC
Escape
Backslash is used to escape special charactersprintln 'Hello\tWorld' // output: Hello World println 'Hi\\There' // output: Hi\There println 'Hi\'There' // output: Hi'There println "Hi\"There" // output: Hi"There
Multiple lines
You can initialize the value of a string with multiple lines, by using either backslash at the end of each line, or enclosing between triple quotes/double-quotes. Here are the different examples and their output:
def str1 = """#1 Hello This is a multi line string example """ println str1 def str2 = '''#2 This is Another multi line string sammple ''' println str2 def str3 = '#3 This is\ a sample with\ backslash' println str3 def str4 = '\n#4 Another example\n\ with backslash\n\ and next line' println str4
This is the output of the code above:
#1 Hello This is a multi line string example #2 This is Another multi line string sammple #3 This isa sample withbackslash #4 Another example with backslash and next line
Padding
Groovy supports padding to make sure a String is of a particular length. For example:
def str = 'ABC'.padLeft(5) println str println str.length()Will output:
ABC 5Notice that the string is padded with 2 blank spaces to the left, to make sure it is 5 characters.
It is also possible to specify the text to pad, if you wish not to use space.
println 'ABC'.padLeft(5,'+') // output: ++ABCYou are not limited to padding a certain character to a String. You can also choose to pad a string. For example:
println 'ABC'.padLeft(10,'123') // output: 1231231ABCThe string "123" are repeated until the required 10 characters is met.
You can pad to the left, right, or center the original string. For example:
println 'ABC'.padLeft(8,'+') // output: +++++ABC println 'ABC'.padRight(8,'+') // output: ABC+++++ println 'ABC'.center(8,'+') // output: ++ABC+++
Tokenize
Tokenizing a string is more convenient in Groovy. For example:
def list1 = 'i am john'.tokenize()Is the same as:
def list1 = ['i', 'am', 'john']By default, it will be tokenized by white spaces (space, tab, next line).
It is possible to tokenize using a specific delimiter:
def a = 'i,am,john'.tokenize() // same as: ['i,am,john'] def b = 'i,am-john'.tokenize(',-') // same as: ['i', 'am', 'john']
Closure
Strings can be manipulated using closures.find will iterate through each character and will return the first character that matches the criteria given. findAll on the other hand, will return all characters that matches the criteria as list. Example:
println 'grails'.find{ it > 'i' } // output: r println 'grails'.findAll{ it > 'i' } // output: [r, l, s] println 'grails'.findAll{ it >= 's' } // output: [s]
every will test each character and will return true if all matches the criteria. These 2 conditions are identical:
def a = 'abc'.every{ it > 'b' } def b = 'abc'[0] > 'b' && 'abc'[1] > 'b' && 'abc'[2] > 'b'
any will test each character and will return true if one of them matches the criteria. These 2 conditions are identical:
def a = 'abc'.any{ it > 'b' } def b = 'abc'[0] > 'b' || 'abc'[1] > 'b' || 'abc'[2] > 'b'
collect will construct a new list by manipulating each character.
'abc'.collect{ it } // ['a', 'b', 'c'] 'abc'.collect{ it + '.' } // ['a.', 'b.', 'c.'] 'abc'.collect{ 'test-' + it } // ['test-a', 'test-b', 'test-c'] 'abc'.collect{ it * 3 } // ['aaa', 'bbb', 'ccc']
Other Groovy Tutorials
- Playing with Groovy Language
- String
- Map
- Array Manipulation
- File Manipulation
- Each Loop
- For Loop
- Times Loop
- String To Integer
- List To String
- Sleep/Delay
- print and println
Plugins
- • Barcode (barcode4j) Plugin Example
- • Spring Security Core Plugin Example - Annotations
- • Spring Security Core Plugin Example - Static URL Map Rules
- • Spring Security Core Plugin Example - Dynamic Request Maps
- • Mail Plugin Tutorial
- • Quartz Plugin Tutorial
- • PayPal Plugin Tutorial
- • Spring Security Core Plugin - Registering Callback Closures
Snippet
- • Improving Performance of Large Batch Insert
- • Add MySQL driver jar to a Grails Project using BuildConfig
- • How To Check If Environment is Test, Development, or Production in Grails
- • How to make Grails use JNDI datasource with Tomcat
- • Grails - How To Create Custom Table Index Or Composite Index
- • Grails Google Maps Geocoding Example
- • Grails Spring Security Core Plugin - Registering Callback Closures
- • Grails Example - Upload Excel Data File To Database
- • Grails render images on the fly in GSP
- • How to make Grails use an external properties file for datasource configuration
- • Grails chained select - load data on one dropdown box depending on another
- • Grails HQL Join Examples
- • Grails HQL Count Examples
- • Grails HQL Update Examples
- • Grails HQL Delete Examples
- • Grails HQL Pagination Examples
- • Grails HQL Group By Examples
- • Grails HQL Order By Examples
- • Grails Criteria Projections Examples
- • Grails Criteria Count Example
Groovy
- • Grails Tutorial for Beginners - Playing with Groovy Language
- • Groovy String Tutorial
- • Groovy Map Tutorial
- • Groovy Each Loop Examples
- • Groovy -e Command Line Option
- • Groovy String To Integer
- • Groovy List To String
- • Groovy Sleep Examples
- • Groovy For Loop Examples
- • Groovy print Examples
- • Groovy println Examples
- • Groovy Times Loop Examples
- • Groovy Array Manipulation Examples
- • Groovy File Examples
- • Groovy Def Declaration Examples
- • Groovy Find
- • Groovy FindAll
- • Groovy Copy File Examples
- • Groovy Array Length
- • Groovy Add To Map Examples
- • Groovy Substring Examples
- • Groovy List Tutorial And Examples
- • Groovy Switch Statement Examples
- • Groovy XmlSlurper Examples for Parsing XML
- • Groovy XmlParser Examples for Parsing XML
- • Groovy Create XML Document Examples
- • Groovy Edit/Modify XML Examples
- • Groovy Sort Information in XML Document
Tag Reference
- • cookie Tag Example
- • actionSubmitImage Tag Example
- • actionSubmit Tag Example
- • checkBox Tag Example
- • AJAX Tag - remoteField Example
- • localeSelect Tag Example
- • timeZoneSelect Tag Example
- • countrySelect Tag Example
- • country Tag Example
- • currencySelect Tag Example
- • textArea Tag Example
- • textField Tag Example
- • while Tag Example
- • unless Tag Example
- • if Tag Example
- • each Tag Examples
- • collect Tag Examples
- • join Tag Examples
- • findAll Tag Examples
- • createLink Tag Example
- • createLinkTo Tag Example
- • datePicker Tag
- • else Tag Example
- • elseif Tag Example
- • formatDate Tag Example
- • formatBoolean Tag Example