1. 概要

このチュートリアルでは、Groovyを使用してStringを連結するいくつかの方法を見ていきます。 ここでは、Groovyオンラインインタープリターが便利です。

まず、 numOfWonder 変数を定義します。これは、例全体で使用します。

def numOfWonder = 'seven'

2. 連結演算子

簡単に言うと、 +演算子を使用して、文字列を結合できます。

'The ' + numOfWonder + ' wonders of the world'

同様に、Groovyは左シフト<<演算子もサポートしています。

'The ' << numOfWonder << ' wonders of ' << 'the world'

3. 文字列補間

次のステップとして、文字列リテラル内の Groovy式を使用して、コードの可読性を向上させます。

"The $numOfWonder wonders of the world\n"

これは、中括弧を使用して実現することもできます。

"The ${numOfWonder} wonders of the world\n"

4. 複数行の文字列

世界のすべての驚異を印刷したいとします。次に、 triple-double-quotes を使用して、numOfWonderを含む複数行のStringを定義できます。 変数:

"""
There are $numOfWonder wonders of the world.
Can you name them all? 
1. The Great Pyramid of Giza
2. Hanging Gardens of Babylon
3. Colossus of Rhode
4. Lighthouse of Alexendra
5. Temple of Artemis
6. Status of Zeus at Olympia
7. Mausoleum at Halicarnassus
"""

5. 連結方法

最後のオプションとして、Stringconcatメソッドを見ていきます。

'The '.concat(numOfWonder).concat(' wonders of the world')​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

非常に長いテキストの場合は、代わりにStringBuilderまたはStringBufferを使用することをお勧めします。

new StringBuilder().append('The ').append(numOfWonder).append(' wonders of the world')
new StringBuffer().append('The ').append(numOfWonder).append(' wonders of the world')​​​​​​​​​​​​​​​

6. 結論

この記事では、Groovyを使用してStringを連結する方法について簡単に説明しました。

いつものように、このチュートリアルの完全なソースコードは、GitHubから入手できます。