// 1694. Reformat Phone Number
class Solution {
public String reformatNumber(String number) {
StringBuilder sb = new StringBuilder();
StringBuilder ans = new StringBuilder();
for (int i = 0; i < number.length(); ++i) {
if (number.charAt(i) >= '0' && number.charAt(i) <= '9') {
sb.append(number.charAt(i));
}
}
int i = 0;
while (i < sb.length() - 4) {
ans.append(sb.charAt(i));
++i;
ans.append(sb.charAt(i));
++i;
ans.append(sb.charAt(i));
++i;
ans.append('-');
}
if (i == sb.length() - 4) {
ans.append(sb.charAt(i));
++i;
ans.append(sb.charAt(i));
++i;
ans.append('-').append(sb.charAt(i));
++i;
ans.append(sb.charAt(i));
} else {
while (i < sb.length()) {
ans.append(sb.charAt(i));
++i;
}
}
return ans.toString();
}
}
学习笔记:
这道题就是将数字提取出来,然后3个一组。
剩下不到4个或刚好4个再进行处理。