简体   繁体   English

Java 中的长字符串达到最大长度时将拆分为行

[英]Long string will split into lines when it reached maximum length in Java

String[] string = {"Terms of service are the legal agreements between a service provider and a person who wants to use that service.", "The person must agree to abide by the terms of service in order to use the offered service."};

Anyone knows how to make a string element in a string array above split into new lines when it reached the maximum length which is, let say 20.任何人都知道如何使上面的字符串数组中的字符串元素在达到最大长度(例如 20)时拆分为新行。

You can use Stream#flatMap along with String#split .您可以将Stream#flatMapString#split一起使用。

int maxLen = 20;
String[] res = Arrays.stream(arr).flatMap(s -> 
     Arrays.stream(s.split("(?<=\\G.{" + maxLen + "})"))).toArray(String[]::new);
// Separate each element based on the maximum length 
System.out.println(Arrays.toString(res));

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

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