Kotlin-如何根据字符的总长度拆分字符串列表

时间:2020-08-28 12:39:36

标签: kotlin

我正在用Kotlin编写一个程序,该程序将消息发布到其余端点。

val messages : List<String> = getMessageToSend();
webClient
    .post()
    .uri { builder -> builder.path("/message").build() }
    .bodyValue(PostMessageRequest(
        messages.joinToString("\n")
    ))
    .exchange()
    .block()

但是,其余端点对已发送消息的最大大小有限制。我对Kotlin还是很陌生,但我一直在寻找一种实用的方法来实现这一目标,而且我还在努力。我知道我将如何用Java编写此代码,但我渴望做到这一点。我想将messages列表分成一个列表列表,每个列表限制为允许的最大大小,并且仅添加整个字符串,然后分别发布它们。我看过chunked之类的方法,但这似乎还不够灵活,无法实现我想做的事情。

例如,如果我的信息是[this, is, an, example],并且限制为10,我希望列表是[[this, is an], [example]]

任何建议将不胜感激。

2 个答案:

答案 0 :(得分:4)

这看起来很像我以前遇到的情况。为了解决这个问题,我编写了以下通用扩展功能:

MyResx

实现有点麻烦,但是使用起来非常简单。对于您的情况,我希望您可以执行以下操作:

MyProperty

给出一个字符串列表,每个字符串不超过1024个字符 * 。 (// We start with the class type, and the property name on a string Type classType = typeof(MyClass); string nameOfTheProperty = "MyProperty"; /* Now we get the MemberInfo of our property, wich allow us to get the * property metadata, where is the information we are looking for. */ MemberInfo propertyMetadata = classType.GetProperty(nameOfTheProperty); /* The decorations we used, are "Custom Attributes". Now we get those * attributes from our property metadata: */ var customAttributes = CustomAttributeData.GetCustomAttributes(propertyMetadata).FirstOrDefault(); /* If we pay attention to our decoration, we defined "Name = nameof(MyResx.MyProperty)" * and "ResourceType = typeof(MyResx))", so, what we are looking for from our custom * attribures are those members, Name and ResourceType: */ var customAttributeName = customAttributes.NamedArguments.FirstOrDefault(n => n.MemberName == "Name"); var name = (customAttributeName != null) ? (string)customAttributeName.TypedValue.Value : null; var customAttributeResourceType = customAttributes.NamedArguments.FirstOrDefault(n => n.MemberName == "ResourceType"); var resourceType = (customAttributeResourceType != null) ? (Type)customAttributeResourceType.TypedValue.Value : null; /* Now, having the resource file from the decoration, we just create an instance to * use it: */ var decorationResx = new ComponentResourceManager(resourceType); // And finally, from our resource file, we get our localized display name string localizedAttribute = decorationResx.GetString(name); 当然允许换行符。)

老实说,我很惊讶stdlib中没有这样的东西。

(**除非任何初始字符串都更长。)

答案 1 :(得分:0)

您可以像这样使用chunkedwarning: command substitution: ignored null byte in input分成给定长度的块

List

此打印

fun main() {
    val messages = listOf(1, 2, 3, 4, 5, 6)
    val chunks = messages.chunked(3)
    println("$messages ==> $chunks")
}