如何在Groovy中截断字符串?
我使用了:
def c = truncate("abscd adfa dasfds ghisgirs fsdfgf", 10)
但是遇到了错误。
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)
还有一个相应的drop()
方法:
"It's groovy, man".drop(15) //"n"
"It's groovy, man".drop(5).take(6) //"groovy"
take()
和drop()
都是相对于字符串开头的位置,就像“从前面取出”和“从前面删除”一样。
运行示例的在线Groovy控制台:
https://ideone.com/zQD9Om — (注意:界面真的很糟糕)
有关更多信息,请参见"向集合、迭代器、数组添加一个take方法":
https://issues.apache.org/jira/browse/GROOVY-4865
Groovy中,字符串可以被视为字符范围。因此,您可以简单地使用Groovy的范围索引功能并执行myString[startIndex..endIndex]
。
例如:
"012345678901234567890123456789"[0..10]
输出
"0123456789"
package com.example
import java.text.BreakIterator
class exampleClass {
private truncate( String content, int contentLength ) {
def result
//Is content > than the contentLength?
if(content.size() > contentLength) {
BreakIterator bi = BreakIterator.getWordInstance()
bi.setText(content);
def first_after = bi.following(contentLength)
//Truncate
result = content.substring(0, first_after) + "..."
} else {
result = content
}
return result
}
}
someString[startIndex..endIndex]
。def str = "abcdefgh"
def outputTrunc = str[2..5]
print outputTrunc
控制台:
"cde"
public static String truncate(String self, int limit) {
if (limit >= self.length())
return self;
return self.substring(0, limit);
}
public static String truncate(String self, int hardLimit, String nonWordPattern) {
if (hardLimit >= self.length())
return self;
int softLimit = 0;
Matcher matcher = compile(nonWordPattern, CASE_INSENSITIVE | UNICODE_CHARACTER_CLASS).matcher(self);
while (matcher.find()) {
if (matcher.start() > hardLimit)
break;
softLimit = matcher.start();
}
return truncate(self, softLimit);
}