-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNameAbbreviator.java
More file actions
61 lines (53 loc) · 2.17 KB
/
Copy pathNameAbbreviator.java
File metadata and controls
61 lines (53 loc) · 2.17 KB
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
59
60
61
public class NameAbbreviator {
/**
* Returns an abbreviated version of a full name.
* All names except the last are abbreviated to a single letter followed by a period.
*
* e.g. "Thomas James Turner" -> "T.J. Turner"
*
* @param fullName the full name to abbreviate
* @return the abbreviated name
*/
public static String abbreviate(String fullName) {
String[] names = fullName.split(" ");
String result = "";
for(int i = 0; i < names.length ; i++) {
if (i == names.length-1) {
if (i > 0) {
result += " ";
}
result += names[i];
} else {
result += names[i].charAt(0) + ".";
}
}
return result;
}
// -------------------------------------------------------------------------
// Test runner
// -------------------------------------------------------------------------
public static void main(String[] args) {
int passed = 0, failed = 0;
Object[][] tests = {
// { input, expected }
{ "Thomas James Turner", "T.J. Turner" }, // basic 3-part name
{ "Tom Turner", "T. Turner" }, // 2-part name
{ "Turner", "Turner" }, // single name (no abbreviation)
{ "A B C D Turner", "A.B.C.D. Turner" }, // many middle names
{ "thomas james turner", "t.j. turner" }, // lowercase preserved
{ "THOMAS JAMES TURNER", "T.J. TURNER" }, // uppercase preserved
};
for (Object[] test : tests) {
String input = (String) test[0];
String expected = (String) test[1];
String actual = abbreviate(input);
boolean ok = expected.equals(actual);
System.out.printf(" %-35s -> %-20s %s%n",
"\"" + input + "\"",
"\"" + actual + "\"",
ok ? "PASS" : "FAIL (expected \"" + expected + "\")");
if (ok) passed++; else failed++;
}
System.out.printf("%nResults: %d passed, %d failed%n", passed, failed);
}
}