Issue
Should write a remove(String arg) functions - It Returns a new string version of the current string where the alphabetical characters specified in the given arg, are removed. The numbers should not be affected.
I tried the below code.
public String remove(String arg) {
if (myString==null || myString == "") {
myString = "";
return this.myString;
}
this.myString = myString.replaceAll(arg,"");
System.out.println(myString);
return myString;
}
JUnit Test Case:
@Test
void testRemove() {
assertEquals("", this.myCustomString.remove(""));
this.myCustomString.setString(null);
assertEquals("", this.myCustomString.remove(""));
this.myCustomString.setString("my lucky numbers are 6, 8, and 19.");
assertEquals("my lucky numbes e 6, 8, nd 19.", this.myCustomString.remove("ra6"));
}
The above test case failed. Error message: AssertionFailedError: expected,my lucky numbes e 6, 8, nd 19.> but was:my lucky numbers are 6, 8, and 19.>
Hope someone can help, Thanks.
Solution
This is because the string that you are trying to replace doesn't present in the actual string.
i.e there is no ra6.
Either you handle character wise or call multiple time your method.
@Test
void testRemove() {
assertEquals("", this.myCustomString.remove(""));
this.myCustomString.setString(null);
assertEquals("", this.myCustomString.remove(""));
this.myCustomString.setString("my lucky numbers are 6, 8, and 19.");
String string = this.myCustomString.remove("r"));
string = string.remove("a"));
string = string.remove("6"));
assertEquals("my lucky numbes e 6, 8, nd 19.", string);
}
Updated method to replace characters.
public String remove(String arg) {
if (myString==null || myString == "") {
myString = "";
return this.myString;
}
for(char c : arg.toCharArray() {
this.myString = myString.replaceAll(String.valueOf(c),"");
}
return myString;
}
Answered By - Pirate
Answer Checked By - Marie Seifert (JavaFixing Admin)