I am going through the CodingBat exercises for Java. I got to this problem:
Return a version of the given string, where for every star (*) in the string the star and the chars immediately to its left and right (if any) are gone. So
"ad"
,"ab*cd"
,"ab**cd"
,"*ead"
, and"ade*"
all yield"ad"
.
I decided to solve this using regular expressions. Here is my code:
public String starOut(String str){
String s = " " + str + " "; //Avoiding OOB exceptions.
String n = ""; //Used for replacements of s.
if (s.contains("***")) {
n = s.replaceAll(".[*][*][*].", "");
s = n;
}
if (s.contains("**")) {
n = s.replaceAll(".[*][*].", "");
s = n;
}
if (s.contains("*")) {
n = s.replaceAll(".[*].", "");
}
String theOne = n.replaceAll("\\s", ""); //Remove whitespace created by s declaration.
return theOne;
}
My code is inefficient and repetitious, and does not account for situations of a string containing more than three *
adjacent to each other. I can't help feeling like I'm missing something obvious of regex that would be a beautifully logical solution.
What would be a good solution to ensure my code utilises regex in an efficient and sensical way? Would it be more appropriate to solve this by looping through characters in the original string?