How to truncate a string in groovy?
How to truncate string in groovy?
I used:
def c = truncate("abscd adfa dasfds ghisgirs fsdfgf", 10)
but getting error.
Solution 1:
The Groovy community has added a take()
method which can be used for easy and safe string truncation.
Examples:
"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)
There's also a corresponding drop()
method:
"It's groovy, man".drop(15) //"n"
"It's groovy, man".drop(5).take(6) //"groovy"
Both take()
and drop()
are relative to the start of the string, as in "take from the front" and "drop from the front".
Online Groovy console to run the examples:
https://ideone.com/zQD9Om — (note: the UI is really bad)
For additional information, see "Add a take method to Collections, Iterators, Arrays":
https://issues.apache.org/jira/browse/GROOVY-4865
Solution 2:
In Groovy, strings can be considered as ranges of characters. As a consequence, you can simply use range indexing features of Groovy and do myString[startIndex..endIndex]
.
As an example,
"012345678901234567890123456789"[0..10]
outputs
"0123456789"
Solution 3:
we can simply use range indexing features of Groovy and do someString[startIndex..endIndex].
For example:
def str = "abcdefgh"
def outputTrunc = str[2..5]
print outputTrunc
Console:
"cde"
Solution 4:
To avoid word break you can make use of the java.text.BreakIterator. This will truncate a string to the closest word boundary after a number of characters.
Example
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
}
}