我有一个包含一些字符串的列表,只有当字符串中的字符长度<=某个限制时,我才想合并/连接字符串。
例如,我们有一个字符串列表:
val xs = List("This is a sentence in index0.", "This is a short sentence.", "This is a very very very loooooooooong sentence.", "This is another short sentence.", "Another one.", "The end!")
concat 限制为 60,这意味着我们必须在将字符串合并到下一个字符串之前查看字符串中字符的长度,并确保字符长度不超过 60。如果合并结果将超过 60,则不要合并并按原样获取元素/字符串,然后移动到下一个元素并尝试与下一个元素合并。
因此,如果我们采用上面的列表,
我们可以通过以下方式检查每个字符串中 char 的长度:
xs.map(_.length)
res: List[Int] = List(29, 25, 48, 31, 12, 8)
由此,我们只能连接索引 0 和 1 处的字符串,保留索引 2 并连接索引 3、4 和 5 处的字符串。生成的字符串列表现在应该如下所示:
val result = List("This is a sentence in index0.This is a short sentence.", "This is a very very very loooooooooong sentence.", "This is another short sentence.Another one.The end!")
假设您不知道列表中将有多少字符串,那么实现这一点的好方法是什么。