views:

43

answers:

1

How to truncate string in groovy

I used :

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

but getting error .

thanks in advance .

+4  A: 

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"
Riduidel
In addition ranges can also be negative with `-1` that means the last character of the string. So whenever you will need to truncate to the last part of a string you can easily do `string[-11..-1]`
Jack
@Riduidel, this is not working when given "012345"[0..20]. I get the results in loop and some will have more and some dont have more characters. It should apply for the string which exceeds 20 chars. thanks
Srinath
In your loop you would need to ensure you only substring if the string is greater than 10, for example, def s = it.size() > 10 ? it[0..10] : it
John Wagenleitner
@john, yeah meanwhile i applied the same logic and works. thanks
Srinath