虽然这不是本意,但是我们完全将 Groovy 作为脚本语言使用。我们可以像 Java 那样(严谨?)定义变量的类型,又可以像 PHP 那样不用定义变量类型,还能自由使用 Maven 仓库中的包。Groovy 满足我们对脚本语言的全部期望。当然,这些都是个人感受,肯定不符合软件工程的实践要求,但是我们用的很开心。
该笔记将整理:在 Groovy 中,常用的字符串操作,以及常见问题处理。
极其常用的字符串操作
// 大小写转换
“lowercase”.toUpperCase()
“UPPERCASE”.toLowerCase()
startsWith endsWith
判断为空
How can I determine if a String is non-null and not only whitespace in Groovy? – Stack Overflow
if(“”) { // false
}
if (myString?.trim()) {
…
}
包含 | contains(), indexOf(), …
DeepSeek / groovy 判断字符串是否包含特定字符
def str = “Hello, Groovy!”
def containsComma = str.contains(‘,’) // 判断是否包含逗号
println containsComma // 输出 true
def str = “Hello, Groovy!”
def hasExclamation = str.indexOf(‘!’) != -1 // 如果找到返回索引,否则返回-1
println hasExclamation // 输出 true
def str = “Hello, Groovy!”
def hasLetterG = str =~ /G/ // 使用模式匹配操作符 =~
println hasLetterG.find() // 输出 true
def str = “Hello, Groovy!”
def charToFind = ‘o’
def containsChar = charToFind in str
println containsChar // 输出 true
def str = “Hello, Groovy!”
def charToFind = ‘v’
println “字符串${str}${str.contains(charToFind) ? ‘包含’ : ‘不包含’}字符 ${charToFind}”
// 输出: 字符串Hello, Groovy!包含字符
// 如果需要检查字符串中是否[……]
READ MORE