在Groovy中使用字串

來源:互聯網
上載者:User

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']

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.