Jaden Casing String

Instructions

Jaden Smith, the son of Will Smith, is the star of films such as The Karate Kid (2010) and After Earth (2013). Jaden is also known for some of his philosophy that he delivers via Twitter. When writing on Twitter, he is known for almost always capitalizing every word.

Your task is to convert strings to how they would be written by Jaden Smith. The strings are actual quotes from Jaden Smith, but they are not capitalized in the same way he originally typed them.

Example:

1
2
Not Jaden-Cased: "How can mirrors be real if our eyes aren't real"
Jaden-Cased: "How Can Mirrors Be Real If Our Eyes Aren't Real"

Note that the Java version expects a return value of null for an empty string or null.


My solution

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
import java.util.Arrays;

public class JadenCase {

public static String toJadenCase(String sentence) {
if (isEmpty(sentence))
return null;

String[] words = sentence.split(" ");

StringBuilder builder = new StringBuilder();

Arrays.stream(words)
.map(JadenCase::capitalizeWord)
.forEach(word -> {
builder.append(word)
.append(" ");
});

return builder.toString().trim();
}

public static String capitalizeWord(String word) {
if (isEmpty(word))
return null;

return word.substring(0, 1).toUpperCase() + word.substring(1);
}

public static boolean isEmpty(String str) {
return str == null || str.isEmpty();
}
}

Better solution

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
import java.util.Arrays;
import java.util.stream.Collectors;

public class JadenCase {

public static String toJadenCase(String phrase) {
if (isEmpty(phrase))
return null;

return Arrays.stream(phrase.split(" "))
.map(JadenCase::capitalizeWord)
.collect(Collectors.joining(" "));
}

public static String capitalizeWord(String word) {
if (isEmpty(word))
return null;

return word.substring(0, 1).toUpperCase() + word.substring(1);
}

public static boolean isEmpty(String str) {
return str == null || str.isEmpty();
}
}

feeling

내가 만든 toJadenCase의 return 전에 trim()을 사용해서 끝에 달리는 “ “을 제거 했는데

내가 Stream에 대해 잘 알지 못해 이와 같이 코드를 만들었던 것이고

다른 사람들의 솔루션을 통해 collect 할 때 Collectors.joining()을 사용하면 trim()을 사용하지 않고도 깔끔하게 String을 이어 줄 수 있다는 것을 알았다.

Java lambda 공부의 필요성을 느낀다.

Share