1. 概述

在本教程中,我们将介绍在 Groovy 中拼接字符串的几种常用方式。建议使用 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. 多行字符串

如果我们想输出多行文本,比如列出七大奇迹,可以使用三引号 """...""" 定义多行字符串,并结合插值:

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

不过,如果拼接内容较多或较复杂,更推荐使用 StringBuilderStringBuffer

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

⚠️ StringBuffer 是线程安全的,但性能略低于 StringBuilder,除非有并发需求,否则优先使用 StringBuilder


6. 总结

本文简单介绍了 Groovy 中拼接字符串的几种常用方式:

  • 使用 +<< 操作符 ✅ 简洁直观
  • 使用字符串插值 $${} ✅ 可读性高
  • 使用三引号定义多行字符串 ✅ 适合模板和长文本
  • 使用 concat()StringBuilderStringBuffer ✅ 更适合复杂拼接场景

如需查看完整代码示例,可访问 GitHub 仓库


原始标题:Concatenate Strings with Groovy