Groovy provides a string function isInteger() that tests if a string is an integer: def num1 = "12345" def num2 = "123.45" assert num1.isInteger() assert !num2.isInteger()
Posts Tagged ‘String’
Get the hash of a string
You can get a quick hash code for a string (and all other objects) in Groovy by simply calling it’s hashCode() method. def message = ‘hello’ println message.hashCode() Which prints 99162322
Generate a UUID
To generate UUIDs we use the java.util.UUID class import java.util.UUID uuid = UUID.randomUUID() For a slightly nicer syntax we can use the a static import of the randomUUID() method import static java.util.UUID.randomUUID uuid = randomUUID() Note that in both cases the randomUUID() method returns an instance of java.util.UUID. If you need an actual [...]
Remove the first character of a string
To remove the first character of a string we can use Groovy’s range index notation. def name = ‘GROOVY’ def substring = name[1..-1] assert substring == ‘ROOVY’
Remove the last character of a string
To remove the last character of a string we can use Groovy’s range index notation. def name = ‘GROOVY’ def substring = name[0..-2] assert substring == ‘GROOV’
Find the last character of a string
To find the last character of a string we can use Groovy’s negative index syntax. def name = ‘GROOVY’ def lastChar = name[-1] assert lastChar == ‘Y’
Test for an empty string
In Groovy, a null or empty string evaluates to a boolean false value, so we can take advantage of this in our code: def s = ” if (s) { println "We’ve got a non empty string!" } else { println ‘String is either null or empty’ } Which, in this case prints: String is [...]
Repeat a string
You can repeat a string in groovy using the multiply function: def divider = ‘-’.multiply(10) Or use the standard multiply operator: def divider = ‘-’ * 10
Create a multiline string
Multi-line strings are created by using the triple double quote. def s = """This is an example of a multi-line String """ println s This is also known as a heredoc string.
