Replacing Occurences of Words in Java

0 min read 193 words

The challenge

You are given a string. You must replace any occurrence of the sequence coverage by covfefe, however, if you don’t find the word coverage in the string, you must add covfefe at the end of the string with a leading space.

The solution in Java code

Option 1:

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

Option 2:

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

Option 3:

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

public class Covfefe {
    private static String trasform(String word) {
        if (word.equals("coverage")) {
            return "covfefe";
        }
        return word;
    }

    public static String covfefe(String tweet) {
        String[] words = tweet.split(" ");
        if(tweet.contains("coverage")){
            return Arrays.asList(words).stream().map(n -> trasform(n)).collect(Collectors.joining(" "));
        }
        return tweet + " covfefe";
    }
}

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;


public class CovfefeTest {
    @Test
    public void basicTest() {
        assertEquals("covfefe", Covfefe.covfefe("coverage"));
        assertEquals("covfefe covfefe", Covfefe.covfefe("coverage coverage"));
        assertEquals("nothing covfefe", Covfefe.covfefe("nothing"));
        assertEquals( "double space  covfefe" ,Covfefe.covfefe("double space "));
        assertEquals("covfefe covfefe", Covfefe.covfefe("covfefe"));
    }
    
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts