java - 使用字符串生成器和拆分的 java 电话格式更改
问题描述
我试图重新格式化字符串电话号码+1(204)867-5309
,首先将中间的点分开,然后检查其输入是否有效,如果不是throw new IllegalArgumentException
. 但是由于某种原因,即使我使用字符串生成器来更改它,数字的输出也不会改变。提前致谢。
public class format{
public static void main (String[] args){
String phone = "204.867.5309";
System.out.println(format(phone));
}
public static String format(String phone){
char [] phoneLine = phone.toCharArray();
String [] split = phone.split("\\.");
for (char c: phoneLine){
if (phoneLine[3]=='.'
&& phoneLine[7]=='.'
&& phoneLine.length == 12
&& Character.isDigit(phoneLine[1])
&& Character.isDigit(phoneLine[0])
&& Character.isDigit(phoneLine[2])
&& Character.isDigit(phoneLine[4])
&& Character.isDigit(phoneLine[5])
&& Character.isDigit(phoneLine[6])
&& Character.isDigit(phoneLine[8])
&& Character.isDigit(phoneLine[9]))
{
StringBuilder sb = new StringBuilder(phone);
sb.append("+1");
sb.insert(2,"(");
sb.insert(6, ")");
sb.insert(10,"-");
}
else {
throw new IllegalArgumentException("not valid");
}
}
return phone;
}
}
解决方案
你能试试下面的代码吗?输出:20(48)67-5309+1
public class PhoneNumberFormat {
public static void main(String[] args) {
String phone = "204.867.5309";
System.out.println(format(phone));
}
public static String format(String phone) {
String[] split = phone.split(".");
split = phone.split("\\.");
String newPhone = "";
for (String s : split) {
newPhone = newPhone + s;
}
char[] phoneLine = newPhone.toCharArray();
StringBuilder sb = new StringBuilder();
for (char c : phoneLine) {
if (phoneLine.length == 10
&& Character.isDigit(phoneLine[1])
&& Character.isDigit(phoneLine[0])
&& Character.isDigit(phoneLine[2])
&& Character.isDigit(phoneLine[4])
&& Character.isDigit(phoneLine[5])
&& Character.isDigit(phoneLine[6])
&& Character.isDigit(phoneLine[8])
&& Character.isDigit(phoneLine[9])) {
sb = new StringBuilder(newPhone);
sb.append("+1");
sb.insert(2, "(");
sb.insert(6, ")");
sb.insert(10, "-");
} else {
throw new IllegalArgumentException("not valid");
}
}
return sb.toString();
}}
推荐阅读
- amazon-web-services - s3,需要从浏览器下载,10GB限制
- javascript - 有没有一种干净的方法可以像 React 一样对 Angular 中的组件进行条件可见性?
- angular - 有没有办法动态更新角度 11 中每个复选框单击的响应值?
- javascript - 如何拼接多个数组元素并相应插入?
- chart.js - Chart.js 在 x 轴上显示我的数据集中不存在的日期
- ios - SwiftUI 中带有丰富 markdown 的文本视图(不仅仅是粗体和斜体文本)
- postgresql - 创建没有数据的表非常慢
- ios - 如何以编程方式下载 TestFlight 构建的构建元数据?
- angular - Angular 10 i18n .htaccess 重定向到子文件夹并从 URL 中删除子文件夹
- python - python中的双向条形图,如何删除所有背景颜色?