Closed. This question needs debugging details。它当前不接受答案。
                        
                    
                
            
        
            
        
                
                    
                
            
                
                    想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                
                    2年前关闭。
            
        

    

我想将字符串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;


它从结尾开始分裂。

最佳答案

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("-"));
}

09-13 05:20