Thursday, November 30, 2023
HomeSoftware EngineeringMethods to Spacify a String in Java

Methods 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("good day world") // returns "h e l l o   w o r l d"

The answer in Java code

Choice 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();
    }
}

Choice 2:

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

Choice 3:

public class Spacify {
    public static String spacify(String str){
        String[] chars = str.break up("");
        return String.be 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("good day 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