CamelCase Method in Java

The challenge

Write a simple CamelCase method for strings.

All words must have their first letter capitalized without spaces.

Example:

// "HelloCase" camelCase("hello case"); // "CamelCaseWord" camelCase("camel case word");
Code language: Java (java)

The solution in Java code

Option 1:

public class Solution { public static String camelCase(String str) { String[] words = str.trim().split("\\s+"); if (words.length==0) return ""; StringBuilder sb = new StringBuilder(); for (int i=0; i<words.length; i++) { String word = words[i]; if (word.length()>1) { String s = word.substring(0, 1).toUpperCase() + word.substring(1, word.length()); sb.append(s); } else { sb.append(word.toUpperCase()); } } return sb.toString(); } }
Code language: Java (java)

Option 2:

import java.util.Arrays; import java.util.stream.Collectors; public class Solution { public static String camelCase(String str) { return (str == null || str.isEmpty())?"":Arrays.stream(str.trim().split("\\s+")) .map(s -> s.substring(0,1).toUpperCase()+s.substring(1,s.length())) .collect(Collectors.joining()); } }
Code language: Java (java)

Option 3:

import org.apache.commons.lang3.text.WordUtils; public class Solution { public static String camelCase(String str) { String result = ""; for(String s : str.trim().split(" ")){ result += WordUtils.capitalize(s); } return result; } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testTwoWords() { assertEquals("TestCase", Solution.camelCase("test case")); } @Test public void testThreeWords() { assertEquals("CamelCaseMethod", Solution.camelCase("camel case method")); } @Test public void testLeadingSpace() { assertEquals("CamelCaseWord", Solution.camelCase(" camel case word")); } @Test public void testTrailingSpace() { assertEquals("SayHello", Solution.camelCase("say hello ")); } @Test public void testSingleLetter() { assertEquals("Z", Solution.camelCase("z")); } @Test public void testTwoSpacesBetweenWords() { assertEquals("AbC", Solution.camelCase("ab c")); } @Test public void testEmptyString() { assertEquals("", Solution.camelCase("")); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments