1 Strings
1.1 Strings and GStrings
Groovy允许你使用2种不同类型的字符串类型,分别是java.lang.String
和groovy.lang.GString
类。在Groovy中,你也可以定义单行或多行的字符串。
字符串使用””,括起来。ofGString
会自动转换为java.lang.String
。
package first
class StringTest {
static main(args) { def name="John" def s1="Hello $name" //$name将会被替换 def s2="Hello $name" println s1 println s2 println s1.class println s2.class //举例对象引用并方法调用 def date = new Date() println "We met at $date" println "We met at ${date.format('yyyy-MM-dd')}" }
}
|
输出
下边表格中,定义了不同类型的Strings。
Table 2. Define Strings in Groovy
String example |
Description |
'This is a String' |
标准的java String |
"This is a GString" |
Groovy GString,允许变量替换和方法调用 |
''' Multiline string (with line breaks)''' |
多行string |
""" Multiline string (with line breaks)""" |
多行GString |
/regularexpression/ |
前后都加/,使得正则表达式更加可读。 |
tokenize()
方法,切割String进入到一个String list,使用空白符作为分隔符。
Groovy JDK增加toURL()
到String,意思是允许一个String转为URL。
trim
方法,删除字符串收尾的空白字符(空格)。
1.2 Operator overloading in Strings
String支持操作重载。使用+连接字符串,使用-截取字符串,使用 left-shift追加到字符串。