Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 350
Srinath Avatar asked Jul 12 '10 07:07

Srinath


People also ask

How to truncate string in Groovy?

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.

What is substring in groovy?

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.


1 Answers

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

like image 186
Dem Pilafian Avatar answered Sep 24 '22 08:09

Dem Pilafian