The “Split Strings” Challenge using Java

The challenge

Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore (‘_’).

Examples:

StringSplit.solution("abc") // should return {"ab", "c_"} StringSplit.solution("abcdef") // should return {"ab", "cd", "ef"}
Code language: Java (java)

Test cases

import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; import java.util.Arrays; public class SampleTest { @Test public void testEvenString() { String s = "abcdef"; String s1 = "HelloWorld"; assertEquals("Should handle even string","[ab, cd, ef]", Arrays.toString(StringSplit.solution(s))); assertEquals("Should handle even string","[He, ll, oW, or, ld]", Arrays.toString(StringSplit.solution(s1))); } @Test public void testOddString() { String s = "abcde"; String s1 = "LovePizza"; assertEquals("Should handle odd string","[ab, cd, e_]", Arrays.toString(StringSplit.solution(s))); assertEquals("Should handle odd string","[Lo, ve, Pi, zz, a_]", Arrays.toString(StringSplit.solution(s1))); } @Test public void testEmptyString() { String s = ""; assertEquals("Should handle empty string","[]", Arrays.toString(StringSplit.solution(s))); } }
Code language: Java (java)

The solution in Java

public class StringSplit { public static String[] solution(String s) { // if it's blank, then return if (s.length()==0) return new String[0]; // if not even, then add an underscore to the end if (s.length()%2!=0) { s+="_"; } // determine the space needed for the return array int spaceNeeded = s.length()/2; // create a new array to populate and return String[] out = new String[spaceNeeded]; // create an builder index int j = 0; // loop through the input string for (int i=0; i<s.length(); i++) { // create a new string to build StringBuilder sb = new StringBuilder(); // add the current item sb.append(s.charAt(i)); // add the next item sb.append(s.charAt(i+1)); // populate our output string as we go out[j] = sb.toString(); // increment both counters i++; j++; } // return the built string return out; } }
Code language: Java (java)

A simple alternative using regular expressions:

public class StringSplit { public static String[] solution(String s) { s = (s.length() % 2 == 0)?s:s+"_"; return s.split("(?<=\\G.{2})"); } }
Code language: Java (java)

Another short regular expression solution:

class StringSplit { static String[] solution(String s) { return (s + (s.length() % 2 > 0 ? "_" : "")).split("(?<=\\G.{2})"); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments