Reputation: 61
I'm still very new to java and I search to replace a part of a string by another, except if the previous character of this string is C,V,M,G or W. I.e. if I get BILLE
as input I want the output give me B.Y.E
but if I get MILLE
as input, I want MILLE
as output.
Here what I've tried :
import java.util.HashMap;
import java.util.Map;
public class Phaille {
static Map<String, String> phaille2 = new HashMap<String, String>();
static {
phaille2.put("ILL", ".Y.");
}
public static String phaille1(final String tampon){
int position= tampon.indexOf("ILL");
String sub=tampon.substring(position,tampon.length());
if (position != -1 ){
if(!(sub.endsWith("C"))){
return phaille2.get(tampon);
}
}
return tampon;
}
}
But when i test with "CYRILLE"
, "CECILLE"
,"ILL"
,"CILLILLILL"
, the test gives to me
org.junit.ComparisonFailure: expected:<null> but was:<"CYR.Y.E">.
Upvotes: 0
Views: 210
Reputation: 34618
The unit test output is a bit confusing (it should probably reverse the order of comparison to make the message reasonable). But basically, what it says is that you are returning null
instead of returning CYR.Y.E
.
You are returning null
because of this line:
return phaille2.get(tampon);
Your tampon
is the original string CYRILLE
. There is no item in phaille2
that matches the key CYRILLE
(there is only an item for ILL
), so the HashMap
returns null
, and this is what you return.
What you are doing is:
ILL
(that's good).tabmpon
from that position forward (why? This will give you ILLE
).C
(it will not, because it will always begin with ILL
because that's what you were searching).tampon
which I already told you does not exist in the hash table.What you should do:
ILL
as you do.If the position is 0, replace ILL
with what the HashTable
contains for "ILL"
(not tampon
).
tampon
from before the position of ILL
that you found,HashTable
tampon
from after the ILL
.You'll probably need to play with this a bit to get the numbers right.
ILL
in the number, and you need to return tampon
as it is.tampon.charAt(position-1)
, and decide whether you need to replace ILL
(as I described above) or not.I advise against using a regular expression, as I don't think it was taught at this point of your class, and it seems from your question that you are supposed to solve this with substring
.
Upvotes: 0
Reputation: 36304
Try this code :
public static void main(String[] args) {
String s1 = "BILLE";
String s2 = "MILLE";
String pattern = "(?<![WCVMG])ILL";
System.out.println(s1.replaceAll(pattern, ".Y."));
System.out.println(s2.replaceAll(pattern, ".Y."));
System.out.println("CYRILLE".replaceAll(pattern, ".Y."));
System.out.println("CILLILLILL".replaceAll(pattern, ".Y."));
}
O/P :
B.Y.E
MILLE
CYR.Y.E
CILL.Y..Y.
Upvotes: 3