-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCapitalizeTitle.java
More file actions
41 lines (39 loc) · 1.19 KB
/
CapitalizeTitle.java
File metadata and controls
41 lines (39 loc) · 1.19 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
class Solution {
public static String changeAllSmall(String str) {
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
public static String CapitalFirst(String str) {
if (str.isEmpty()) {
return str;
}
StringBuilder sb = new StringBuilder();
char first = str.charAt(0);
char ch = Character.toUpperCase(first);
sb.append(ch);
sb.append(str.substring(1).toLowerCase());
return sb.toString();
}
public String capitalizeTitle(String title) {
if (title == null || title.isEmpty()) {
return title;
}
String[] arr = title.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
String str = arr[i];
if (str.length() <= 2) {
sb.append(changeAllSmall(str));
} else {
sb.append(CapitalFirst(str));
}
if (i < arr.length - 1) {
sb.append(" ");
}
}
return sb.toString();
}
}