Sunday, April 14, 2024
HomeSoftware EngineeringThe way to Spacify a String in Java

The way to Spacify a String in Java


The problem

Modify the spacify perform in order that it returns the given string with areas inserted between every character.

spacify("hiya world") // returns "h e l l o   w o r l d"

The answer in Java code

Possibility 1:

import java.util.*;
import java.util.stream.*;

public class Spacify {
    public static String spacify(String str){
        return Arrays.stream(str.break up(""))
                .map(c -> c+" ")
                .accumulate(Collectors.becoming a member of())
                .trim();
    }
}

Possibility 2:

public class Spacify {
    public static String spacify(String str){
        return str.replaceAll("", " ").trim();
    }
}

Possibility 3:

public class Spacify {
    public static String spacify(String str){
        String[] chars = str.break up("");
        return String.be a part of(" ", chars);
    }
}

Take a look at instances to validate our answer

import org.junit.Take a look at;

import static org.junit.Assert.*;

public class SpacifyTest {
    @Take a look at
    public void basicTest() {
         assertEquals("h e l l o   w o r l d",Spacify.spacify("hiya world"));
         assertEquals("1 2 3 4 5",Spacify.spacify("12345"));
    }
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments