-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChangeCase.java
76 lines (66 loc) · 2.46 KB
/
ChangeCase.java
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.smlnskgmail.jaman.codewarsjava.kyu6;
import java.util.stream.Collectors;
// https://www.codewars.com/kata/591cac98a6007e87d900013a
public class ChangeCase {
private final String input;
public ChangeCase(String input) {
this.input = input;
}
public String toSentenceCase() {
boolean capitalizeNeeded = true;
char[] chars = input.toCharArray();
for (int i = 0; i < input.length(); i++) {
if (capitalizeNeeded && Character.isAlphabetic(chars[i])) {
chars[i] = Character.toUpperCase(chars[i]);
capitalizeNeeded = false;
} else {
chars[i] = Character.toLowerCase(chars[i]);
if (chars[i] == '.' || chars[i] == '?' || chars[i] == '!') {
capitalizeNeeded = true;
}
if (chars[i] == ',' || chars[i] == ' ' || Character.isDigit(chars[i])) {
capitalizeNeeded = false;
}
}
}
return new String(chars);
}
public String toLowerCase() {
return input.toLowerCase();
}
public String toUpperCase() {
return input.toUpperCase();
}
public String capitalizeEachWord() {
boolean capitalizeNeeded = true;
char[] chars = input.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (capitalizeNeeded && Character.isAlphabetic(chars[i])) {
chars[i] = Character.toUpperCase(chars[i]);
capitalizeNeeded = false;
} else if (Character.isAlphabetic(chars[i])) {
chars[i] = Character.toLowerCase(chars[i]);
} else {
capitalizeNeeded = !Character.isDigit(chars[i]);
}
}
return new String(chars);
}
public String toToggleCase() {
return input
.chars()
.mapToObj(operand -> {
char value = (char) operand;
if (Character.isLetter(value)) {
return String.valueOf(
Character.isLowerCase(value)
? Character.toUpperCase(value)
: Character.toLowerCase(value)
);
} else {
return String.valueOf(value);
}
})
.collect(Collectors.joining());
}
}