Printing a sequence of 3-by-3 formatted numbers separated by dashes

1

Let's say I have the following String S = "00-44 48 5555 8361" entry and I need to return this 3-by-3 split string separated by "-" as follows:

  

Output: 004-448-555-583-61

The number of characters may vary. Below the following scope:

public class Solution{
    public static String solution(String S){
    }
}

public static void main(String[] args) {    
        String S = "00-44  48 5555 8361";   
        System.out.print(solution(S));

    }

}

In an effective way, how to solve this in Java 8?

    
asked by anonymous 17.10.2018 / 04:26

1 answer

1

Regex makes magic:

class Solution {
    public static void main(String[] args) {
        String s = "00-44  48 5555 8361";
        System.out.println(solution(s));
        String s2 = "00-44  48 5555 8361 xxx 1";
        System.out.println(solution(s2));
        String s3 = "12345";
        System.out.println(solution(s3));
    }

    public static String solution(String s) {
        return s.replaceAll("[^\d]", "").replaceAll("...", "$0-").replaceAll("-$", "");
    }
}

Here's the output:

004-448-555-583-61
004-448-555-583-611
123-45

See here working on ideone.

Explanation:

17.10.2018 / 06:45