Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 7 Next »

We can use either single- or double-quotes around strings:

Backslashes can escape other characters in Strings. We can use letter codes (eg '\b') or octal codes (eg '\010'):

To span multiple lines, use either triple quotes or a backslash at the end of the continuing lines to join them with the next:

We can also use three double-quotes.

When using double-quotes, either one or three, we can embed code within them using $. Here, they're called GStrings:

Anything more complex than a variable name must be surrounded by curlies:

We can change the variable's value in the GString:

String methods

We can convert other objects in Groovy to their string representation in different ways:

To find the size and substrings:

There's different ways to construct a string:

We can pad and center strings:

We can split a string into tokens:

Some additional methods:

We can use operators on strings:

We can subscript strings just as we can lists, except of course strings are read-only:

We can format values into a string, using format():


A StringBuffer is a mutable string. (But from Java 5.0 onwards, we should use a StringBuilder instead, because StringBuffers are normally reserved for multi-threaded processing.)

To find the size and substrings:

To append to a StringBuffer:

Note that << doesn't yet work with StringBuilders.

If we append to a String, a StringBuffer is returned:

As with strings, we can subscript a StringBuffer, returning a string:

We can insert into, replace within, and delete from StringBuffers using methods:

We can find the index of substrings:

Some miscellaneous methods:

We can enquire of code points in a String or StringBuffer using methods on them, just as we can with methods on Character:

We can manipulate the implementation of a StringBuffer:

  • No labels