Contents

Groovy中String连接

1. 概述

在本教程中,我们将介绍几种使用 Groovy连接String的方法。

我们将首先定义一个numOfWonder变量,我们将在整个示例中使用它:

def numOfWonder = 'seven'

2. 连接运算符

很简单,我们可以使用+ 运算符 来加入String

'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. 多行字符串

假设我们要打印世界上所有的奇迹,那么我们可以使用三双引号 来定义一个多行String,仍然包括我们的numOfWonder变量:

"""
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. 连接方法

作为最后的选择,我们将看看 String的 concat方法:

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