Groovy支援兩種類型字串:一般的Java字串,它是java.lang.String的執行個體;和GStrings,它是 groovy.lang.GString的執行個體,並且允許文本中包含預留位置。GStrings並不是String的子類,因為String 類是最終類(final class)不能被繼承。然而,GString與一般的字串一樣,因為Groovy能將 GStrings轉型為Java strings。
GString 適用於編寫模板代碼(templating),因為您必須動態構建字串(GStrings are useful in templating situations where you have to build your string dynamicly)。以下的清單給出了 一個例子。
使用GStrings:
firstWord = 'Hello'
secondWord = 'dlroW'
println "$firstWord ${secondWord.reverse()}"
結果如下:
Hello World
GStrings不同於Java strings在於它們允許以${..}的文法嵌入變數。如果一個字串由雙引號或三 重引號括起來,並且包含一個非轉義符(unescaped)$,它必定是groovy.lang.GString的一個執行個體;否 則,就是java.lang.String的一個執行個體。
${..}裡可以包含任意有效Groovy運算式,包括方法調用或變數名。只有調用GString的toString方 法時(例如,把結果輸出到控制台),${..}運算式才被求值。
Groovy支援的另一種字串便是java.lang.String。然而,GDK還是動態注入許多協助方法,使其易 於應用。
以下的例子展示了在Groovy中聲明一個字串的不同方式:
s1 = "Hello \"World\" " //Escape double quotes,轉義雙引號
s2 = 'Hello "World" '
assert s1 == s2
s3 = 'Hello \'World\' ' //Escape single quotes,轉義單引號
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']