Created
July 4, 2019 03:50
-
-
Save hardikm9850/c4ec2578b298c094a7b570e8181d9063 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Ideone { | |
static String formatPhone(String s) { | |
s = s.replaceAll(" ", "").replaceAll("-", ""); | |
char[] array = s.toCharArray(); | |
StringBuilder sb = new StringBuilder(); | |
boolean shouldThree = array.length % 3 == 0; | |
for (int i = 0, j = 0; i < array.length; i++) { | |
if (i == array.length - 2 && !shouldThree) { | |
if (sb.charAt(sb.length() - 1) != '-') { | |
sb.append("-"); | |
} | |
sb.append(array[i]); | |
continue; | |
} | |
sb.append(array[i]); | |
j++; | |
if (j % 3 == 0) { | |
sb.append("-"); | |
j = 0; | |
} | |
} | |
if (sb.charAt(sb.length() - 1) == '-') { | |
sb.deleteCharAt(sb.length() - 1); | |
} | |
return sb.toString(); | |
} | |
public static void main(String[] args) throws java.lang.Exception { | |
// your code goes here | |
String answer = formatPhone("1111222212121212121212"); | |
System.out.println(answer); | |
answer = formatPhone("123"); | |
System.out.println(answer); | |
answer = formatPhone("1234"); | |
System.out.println(answer); | |
answer = formatPhone("12345"); | |
System.out.println(answer); | |
answer = formatPhone("1234567"); | |
System.out.println(answer); | |
answer = formatPhone("111122221212121212121"); | |
System.out.println(answer); | |
answer = formatPhone("11112222121212121212"); | |
System.out.println(answer); | |
answer = formatPhone("111122221212121212"); | |
System.out.println(answer); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment