我想将字符串s分成n个部分,并用破折号分隔。这是功能:
public String answer (String s, int n){}
例如,这应该发生:
Example test: ('2-4A0r7-4k', 4)
expect 24A0-R74K
Example test: ('2-4A0r7-4k', 3)
expect 24-A0R-74K
我这样做了,但是给出了错误的答案:
String[] arr = s.split("-", k+1);
s = Arrays.toString(arr);
return s;
它从结尾开始分裂。
答案 0 :(得分:1)
public static String split(String str, int n) {
final Function<String, String> reverse = s -> new StringBuilder(s).reverse().toString();
String[] parts = reverse.apply(str.replaceAll("-", "")).split("(?<=\\G.{" + n + "})");
return IntStream.range(0, parts.length).mapToObj(i -> reverse.apply(parts[parts.length - i - 1])).collect(Collectors.joining("-"));
}