How to Spacify a String in Java

The challenge

Modify the spacify function so that it returns the given string with spaces inserted between each character.

spacify("hello world") // returns "h e l l o w o r l d"
Code language: JavaScript (javascript)

The solution in Java code

Option 1:

import java.util.*; import java.util.stream.*; public class Spacify { public static String spacify(String str){ return Arrays.stream(str.split("")) .map(c -> c+" ") .collect(Collectors.joining()) .trim(); } }
Code language: Java (java)

Option 2:

public class Spacify { public static String spacify(String str){ return str.replaceAll("", " ").trim(); } }
Code language: Java (java)

Option 3:

public class Spacify { public static String spacify(String str){ String[] chars = str.split(""); return String.join(" ", chars); } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.junit.Assert.*; public class SpacifyTest { @Test public void basicTest() { assertEquals("h e l l o w o r l d",Spacify.spacify("hello world")); assertEquals("1 2 3 4 5",Spacify.spacify("12345")); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments