Sunday, April 14, 2024
HomeSoftware EngineeringChanging Occurences of Phrases in Java

Changing Occurences of Phrases in Java


The problem

You’re given a string. It’s essential to exchange any incidence of the sequence protection by covfefe, nevertheless, should you don’t discover the phrase protection within the string, it’s essential to add covfefe on the finish of the string with a number one area.

The answer in Java code

Choice 1:

public class Covfefe {
    public static String covfefe(String tweet) {
        return tweet.comprises("protection") ?
                tweet.replaceAll("protection", "covfefe") :
                tweet+" covfefe";
    }
}

Choice 2:

public class Covfefe {
    public static String covfefe(String tweet) {
        String res;
        res = tweet.exchange("protection", "covfefe");
        if(res.equals(tweet)){
          res = res + " covfefe";
        }
        return res;
    }
}

Choice 3:

import java.util.Arrays;
import java.util.stream.Collectors;

public class Covfefe {
    non-public static String trasform(String phrase) {
        if (phrase.equals("protection")) {
            return "covfefe";
        }
        return phrase;
    }

    public static String covfefe(String tweet) {
        String[] phrases = tweet.break up(" ");
        if(tweet.comprises("protection")){
            return Arrays.asList(phrases).stream().map(n -> trasform(n)).accumulate(Collectors.becoming a member of(" "));
        }
        return tweet + " covfefe";
    }
}

Take a look at circumstances to validate our answer

import org.junit.Take a look at;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;


public class CovfefeTest {
    @Take a look at
    public void basicTest() {
        assertEquals("covfefe", Covfefe.covfefe("protection"));
        assertEquals("covfefe covfefe", Covfefe.covfefe("protection protection"));
        assertEquals("nothing covfefe", Covfefe.covfefe("nothing"));
        assertEquals( "double area  covfefe" ,Covfefe.covfefe("double area "));
        assertEquals("covfefe covfefe", Covfefe.covfefe("covfefe"));
    }
    
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments