Concatenate Strings with Groovy – 用Groovy串联字符串

最后修改: 2019年 7月 21日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll look at several ways to concatenate Strings using Groovy. Note that a Groovy online interpreter comes in handy here.

在本教程中,我们将研究使用Groovy连接Strings的几种方法。请注意,Groovy在线解释器在这里派上用场。

We’ll start by defining a numOfWonder variable, which we’ll use throughout our examples:

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

def numOfWonder = 'seven'

2. Concatenation Operators

2.连接操作符

Quite simply, we can use the + operator to join Strings:

很简单,我们可以使用+操作符来连接Strings。

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

Similarly, Groovy also supports the left shift << operator:

同样地,Groovy也支持左移<<操作符。

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

3. String Interpolation

3.字符串插值

As a next step, we’ll try to improve the readability of the code using a Groovy expression within a string literal:

作为下一步,我们将尝试使用字符串字面内的Groovy表达式来提高代码的可读性。

"The $numOfWonder wonders of the world\n"

This can also be achieved using curly braces:

这也可以用大括号来实现。

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

4. Multi-line Strings

4.多行字符串

Let’s say we want to print all the wonders of the world, then we can use the triple-double-quotes to define a multi-line String, still including our numOfWonder variable:

假设我们想打印世界上所有的奇迹,那么我们可以使用triple-double-quotes来定义一个多行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. Concatenation Methods

5.串联方法

As a final option, we’ll look at String‘s concat method:

作为最后的选择,我们来看看Stringconcat方法。

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

For really long texts, we recommend using a StringBuilder or a StringBuffer instead:

对于真正的长文本,我们建议使用StringBuilderStringBuffer代替。

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

6. Conclusion

6.结论

In this article, we had a quick look at how to concatenate Strings using Groovy.

在这篇文章中,我们快速了解了如何使用Groovy连接Strings。

As usual, the full source code for this tutorial available over on GitHub.

像往常一样,本教程的完整源代码可在GitHub上找到