如何在groovy中截断一个字符串?

Sri*_*ath 35 groovy truncate

如何在groovy中截断字符串?

我用了:

def c = truncate("abscd adfa dasfds ghisgirs fsdfgf", 10)
Run Code Online (Sandbox Code Playgroud)

但得到错误.

Dem*_*ian 73

Groovy社区添加了一个take()方法,可用于简单安全的字符串截断.

例子:

"abscd adfa dasfds ghisgirs fsdfgf".take(10)  //"abscd adfa"
"It's groovy, man".take(4)      //"It's"
"It's groovy, man".take(10000)  //"It's groovy, man" (no exception thrown)
Run Code Online (Sandbox Code Playgroud)

还有一个相应的drop()方法:

"It's groovy, man".drop(15)         //"n"
"It's groovy, man".drop(5).take(6)  //"groovy"
Run Code Online (Sandbox Code Playgroud)

两者take()drop()是相对于开始的字符串,如"取从前面""从前面滴".

运行示例的在线Groovy控制台:
https://ideone.com/zQD9Om - (注意:UI非常糟糕)

有关其他信息,请参阅"向集合,迭代器,数组添加take方法":https:
//issues.apache.org/jira/browse/GROOVY-4865


Rid*_*del 8

在Groovy中,字符串可以被视为字符范围.因此,您可以简单地使用Groovy的范围索引功能myString[startIndex..endIndex].

举个例子,

"012345678901234567890123456789"[0..10]
Run Code Online (Sandbox Code Playgroud)

输出

"0123456789"
Run Code Online (Sandbox Code Playgroud)

  • 在循环中,如果字符串大于10,则需要确保只有子字符串,例如,def s = it.size()> 10?它[0..10]:它 (3认同)
  • 另外,范围也可以是负数,-1表示字符串的最后一个字符.因此,无论何时需要截断到字符串的最后一部分,您都可以轻松地执行`string [-11 ..- 1]` (2认同)