简体   繁体   English

如何在 Groovy 脚本中按 bodySize 拆分字符串

[英]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?您看,我对 Groovy Script 非常非常陌生,我有一个问题:如何根据 String 的主体大小将其分开?

Assuming that the String has a size of 3,000 characters getting the body like假设 String 的大小为 3,000 个字符

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).我应该能够将它分成 500 个字符的段并将每个段保存在不同的变量中(稍后我将在属性中设置)。

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.这将正文拆分为一个字符列表,将它们整理成 500 个长度的组,然后将每个组连接回一个字符串。

As a small example作为一个小例子

def body = 'abcdefghijklmnopqrstuvwxyz'

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

Then segments equals然后segments等于

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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