简体   繁体   中英

How to split a String by bodySize in Groovy Script

Before anything else, I hope that this world situation is not affecting you too much and that you can be as long as possible at home and in good health.

You see, I'm very, very new to Groovy Script and I have a question: How can I separate a String based on its body size?

Assuming that the String has a size of 3,000 characters getting the body like

def body = message.getBody (java.lang.String) as String 

and its size like

def bodySize = body.getBytes (). Length  

I should be able to separate it into 500-character segments and save each segment in a different variable (which I will later set in a property).

I read some examples but I can't adjust them to what I need.

Thank you very much in advance.

Assuming it's ok to have a List of segment strings, you can simply do:

def segments = body.toList().collate(500)*.join()

This splits the body into a list of characters, collates these into 500 length groups, and then joins each group back to a String.

As a small example

def body = 'abcdefghijklmnopqrstuvwxyz'

def segments = body.toList().collate(5)*.join()

Then segments equals

['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy', 'z']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM