How to truncate string in groovy?
I used:
def c = truncate("abscd adfa dasfds ghisgirs fsdfgf", 10)
but getting error.
The Groovy community has added a take() method which can be used for easy and safe string truncation. Both take() and drop() are relative to the start of the string, as in "take from the front" and "drop from the front". Show activity on this post. In Groovy, strings can be considered as ranges of characters.
Groovy - subString() Advertisements. Returns a new String that is a substring of this String. This method has 2 different variants. String substring(int beginIndex) − Pad the String with the spaces appended to the right.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With