close up of a colorful weaving machine

超越基础:Apache Groovy 高级字符串

无论您是经验丰富的 Java 开发人员,希望扩展您的工具箱,还是好奇的新手,理解…
首页 » 博客 » 超越基础:Apache Groovy 高级字符串

掌握基本的字符串操作在任何编程语言中都至关重要,而 Groovy 以其简洁的语法和强大的功能将事情提升到了一个新的水平。

在我之前的文章中,我重新介绍了 Java 和 Groovy String 类。这一次,我将看看 Groovy 关于字符串操作的语法报告。(如果您尚未安装 Groovy,请阅读本介绍 到这系列。)

您已经看到了使用三引号或三撇号来分隔多行字符串块。您还看到了使用范围索引而不是 Java .substring() 方法。

Groovy 的 as 运算符是促进转换的好方法,转换通常是从 String 到某种数值类型

1 int fortyTwo = "42" as int
2 println "fortyTwo = $fortyTwo; class = ${fortyTwo.class}"

运行时产生

 $ groovy Groovy10a.groovy
 fortyTwo = 42; class = class java.lang.Integer

在 Java 中,引号分隔字符常量,但在 Groovy 中,引号分隔字符串常量。当需要 char 值时,as 关键字非常方便

1 char charC = "C" as char
2 println "charC = $charC; class = ${charC.class}"

这会产生

 $ groovy Groovy10b.groovy
 charC = C; class = class java.lang.Character

与 Java 中一样,您可以使用 + 连接字符串,* 创建多个副本,以及 从另一个字符串中删除字符串的第一次出现

1  String fooBar = "foo" + " " + "bar"
2  println "fooBar = $fooBar"
3  String fooFooBar = "foo" * 2 + "bar"
4  println "fooFooBar = $fooFooBar"
5  String fooBar2 = fooFooBar - "foo"
6  println "fooBar2 = $fooBar2"

这会产生

$ groovy Groovy10c.groovy
fooBar = foo bar
fooFooBar = foofoobar
fooBar2 = foobar

在 Groovy 中,+ 运算符实际上使用类定义的 plus() 方法。* 运算符使用从 CharSequence 类继承的 multiply() 方法。- 运算符使用同样从 CharSequence 类继承的 minus() 方法。这允许重写这些方法(或在新类上定义它们)以使用这些运算符。

Groovy 中常见的另一个运算符是 <<,例如对于 List 实例而言,它与 append() 方法关联。然而,由于 String 对象是不可变的,因此将 <<append() 应用于 String 对象不会更改 String 对象本身。相反,它返回一个 StringBuffer 结果

1  def foo = "foo"
2  def fooBar = foo << "bar"
3  println "foo $foo fooBar $fooBar fooBar.class ${fooBar.class}"

运行时产生

$ groovy Groovy10d.groovy
foo foo fooBar foobar fooBar.class class java.lang.StringBuffer

与 Java 中一样,反斜杠字符 \ 必须转义才能出现在字符串中。例如,另一个操作系统中的路径名,例如

C:\TEMP\STUFF

必须写成

"C:\TEMP\STUFF"

这允许反斜杠出现在字符串中(并且不被解释为转义字符。)Groovy 添加了 slashy 字符串,它不需要转义反斜杠

1  String s1 = "C:\\TEMP\\STUFF"
2  String s2 = /C:\TEMP\STUFF/
3  println "s1 $s1 s2 $s2 (s1 == s2) ${s1 == s2}"
4  println "s1.class ${s1.class} s2.class ${s2.class}"

这会产生

$ groovy Groovy10e.groovy
s1 C:\TEMP\STUFF s2 C:\TEMP\STUFF (s1 == s2) true
s1.class class java.lang.String s2.class class java.lang.String

Slashy 字符串真正发挥作用的地方是处理正则表达式,正则表达式通常布满了定义特殊字符的反斜杠。Slashy 字符串消除了转义这些反斜杠的需要。

为了完整性,还有一种 dollar-slashy 字符串,用于创建多行 GString 实例,但我发现它不太有用。

结论

Groovy 向该语言添加了几个运算符和类似运算符的东西,以使字符串的使用更加方便。

作者

如果您喜欢这篇文章,您可能也喜欢这些