Skip to content

Replacing Occurences of Words in Java

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"; } }
Code language: Java (java)

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; } }
Code language: Java (java)

Option 3:

import java.util.Arrays; import; 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"; } }
Code language: Java (java)

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")); } }
Code language: Java (java)

See also  Remove hash from window.location in Javascript
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x