如何在Groovy中截断字符串?

56

如何在Groovy中截断字符串?

我使用了:

def c = truncate("abscd adfa dasfds ghisgirs fsdfgf", 10)

但是遇到了错误。

5个回答

112

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


11

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

例如:

"012345678901234567890123456789"[0..10]

输出

"0123456789"

2
此外,范围也可以是负数,用“-1”表示字符串的最后一个字符。因此,每当您需要截断字符串的最后一部分时,您可以轻松地执行“string[-11..-1]”。 - Jack
1
当给定"012345"[0..20]时,这段代码无法正常工作。我在循环中得到了结果,有些结果会有更多的字符,而有些则没有。它应该适用于超过20个字符的字符串。谢谢。 - Srinath
3
在您的循环中,您需要确保仅在字符串大于10时才进行子字符串操作。例如,def s = it.size() > 10 ? it[0..10] : it - John Wagenleitner
@john,是的,与此同时我应用了相同的逻辑并且有效。谢谢。 - Srinath
1
范围索引很好用,但如果字符串长度小于10个字符,Groovy会抛出StringIndexOutOfBoundsException异常。 - Nik Reiman

2
为了避免断词,您可以使用java.text.BreakIterator。它将在若干个字符后将字符串截断到最接近的单词边界处。 示例:
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
    }
}

2
我们可以简单地使用Groovy的范围索引功能,并执行someString[startIndex..endIndex]
例如:
def str = "abcdefgh"
def outputTrunc = str[2..5]
print outputTrunc

控制台:

"cde"

1
这仅适用于小限制。例如,String bla = ha [0..2047] 将始终失败并引发 StringIndexOutOfBoundsException 异常。正在寻找更好的解决方案。 - John Little
@JohnLittle:你的解决方案在这里 - Wiktor Stribiżew

1
这是我解决这种问题的辅助函数。在许多情况下,您可能希望按单词而不是按字符截断,因此我也粘贴了该函数的代码。
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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接