0

If we have below two formats for phone number in string array.

YYYXXXZZZ , YYY-XXX-ZZZZ

and we want to normalize these phone numbers to :

XXX-YYY-ZZZZ.

How can we do it?

Tom S
  • 39
  • 7

2 Answers2

0

Just extract the substrings based upon the detected format.

if (!p.contains("-")) {
  normalized = p.substring(3, 6) + "-" + p.substring(0, 3) + "-" + p.substring(6);
} else {
  normalized = p.substring(4, 7) + "-" + p.substring(0, 3) + "-" + p.substring(8);
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

I believe you accidentally inserted an extra "Y" for your expected result. EDIT: It has been corrected

public void formatNumber (String number) {
  String formatted=number.substring(3,6)+"-"+number.substring(0,3)+"-"+ number.substring(6);
  return formatted;
}
Kartik Chugh
  • 1,104
  • 14
  • 28