반응형
자바(JAVA) 실습 - 카드번호 마스킹 예시
마스킹 예시
ex. 010-1234-5678 --> 010-12**-56**
ex. 010-124-5678 --> 010-1**-56**
ex. 01012345678 --> 01012**56**
ex. 0101245678 --> 0101**56**
StringBuilder, charArray 활용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58 |
public class MaskingPhoneNumber {
private static final String testCase1 = "010-1234-5678";
private static final String testCase2 = "010-124-5678";
private static final String testCase3 = "01012345678";
private static final String testCase4 = "0101245678";
private static String maskingPhoneWithBar(String phoneNumber) {
if (phoneNumber.isEmpty())
return "";
String result = "";
if (phoneNumber.contains("-")) {
String[] phoneParts = phoneNumber.split("-");
String first = phoneParts[0].toString();
StringBuilder sb1 = new StringBuilder();
char[] charPart1 = phoneParts[1].toCharArray();
for (int i = 0; i < charPart1.length; i++) {
if (charPart1.length >= 4) {
sb1.append(i >= 2 ? "*" : charPart1[i]);
} else {
sb1.append(i >= 1 ? "*" : charPart1[i]);
}
}
String second = sb1.toString();
StringBuilder sb2 = new StringBuilder();
char[] charPart2 = phoneParts[2].toCharArray();
for (int i = 0; i < charPart2.length; i++) {
sb2.append(i >= 2 ? "*" : charPart2[i]);
}
String third = sb2.toString();
result = String.join("-", first, second, third);
} else {
StringBuilder sb = new StringBuilder();
char[] chars = phoneNumber.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars.length >= 11) {
sb.append((i >= 5 && i <= 6 || i >= 9) ? "*" : chars[i]);
} else {
sb.append((i >= 4 && i <= 5 || i >= 8) ? "*" : chars[i]);
}
}
result = sb.toString();
}
return result;
}
public static void main(String[] args) {
String result = "";
result = maskingPhoneWithBar(testCase1);
System.out.printf("%-14s %6s %-14s\n", testCase1, " --> ", result);
result = maskingPhoneWithBar(testCase2);
System.out.printf("%-14s %6s %-14s\n", testCase2, " --> ", result);
result = maskingPhoneWithBar(testCase3);
System.out.printf("%-14s %6s %-14s\n", testCase3, " --> ", result);
result = maskingPhoneWithBar(testCase4);
System.out.printf("%-14s %6s %-14s\n", testCase4, " --> ", result);
}
}
|
반응형