Groovy supports two types of strings: A generic Java string, an instance of java.lang.String, and Gstrings, which is an instance of groovy.lang.GString, and allows the text to contain placeholders. Gstrings is not a subclass of string because the string class is the final class (final Class) that cannot be inherited. However, Gstring is the same as a generic string, because groovy can transform gstrings into Java strings.
Gstring is useful for writing template code (templating) because you must dynamically build a string (Gstrings are useful in templating situations where and have to build your Strin G dynamicly). The following list gives an example.
Use gstrings:
FirstWord = ' Hello '
Secondword = ' Dlrow '
println "$firstWord
${secondword.reverse ()}"
The results are as follows:
Hello World
Gstrings differs from the Java strings in that they allow ${.} The syntax of the embedded variable. If a string is enclosed in double or triple quotes and contains a non-escape character (unescaped) $, it must be an instance of groovy.lang.GString; otherwise, it is an instance of java.lang.String.
${..} Can contain any valid groovy expressions, including method calls or variable names. Only when the Gstring ToString method is invoked (for example, to output the result to the console), ${.} An expression is evaluated.
Another string that groovy supports is java.lang.String. However, GDK also dynamically injects many help methods to make them easy to apply.
The following example shows the different ways to declare a string in groovy:
S1 = "Hello \" world\ ""//escape double quotes, escape double quotes
S2 = ' Hello ' World '
assert S1 = = S2
s3 = ' Hello \ ' world\ '//escape single quotes, escape apostrophe
S4 =
"Hello ' World" "
Assert S3 = = S4
Assert new String (' Hello world ') = = "Hello World
"
def s = [' h ', ' e ', ' l ', ' l ', ' o '] as char[]
Assert new String (s) = =
' Hello '
Assert new String (s,0,4) = = ' hell '
S.eachwithindex{ch,index-> Assert ch = =
S[index]}
Assert ' Hello '. ToCharArray () = = [' h ', ' e ', ' l ', ' l ', ' O ']