This may have been asked somewhere else – unfortunately it’s quite a difficult thing to google for.
Regularly when programming I find myself with constructs of the form (I’m looking particularly for a Java answer, but I’d be fascinated by a general solution)
String a = getStringFromPlace();
a=processStringInSomeWay(a);
sendStringToSomePlace(a);
My problem is that processStringInSomeWay(a) breaks if given some particular character, “£”, say, and so I end up writing this…
String a = getStringFromPlace();
a=a.replace("£","replacevalue");
a=processStringInSomeWay(a);
a=a.replace("replacevalue","£");
sendStringToSomePlace(a);
but this, of course, breaks if ‘replacevalue’ happens to be in the input. I could just choose a ridiculous value of ‘replacevalue’ but that’s clearly not good practice. What is the best practice in this situation?
EDIT – this is in the particualar case where one does not have control over the ‘processStringInSomeWay()’ method. And I’m also interested in the situation were a has to be processed as one unit, it can’t be split.
Your question is quite generic in the sense that without knowing what you need to do with these strings is almost impossible to give one precise answer.
Solutions I see are:
replaceAll("£",""))replaceAll("£",escape+"£"))This problem is common in many situations and from what I saw you usually end up by just deciding that you have a sequence which can’t be used naturally because it’s used as an escape sequence. This is true in compression protocols, network protocols and in many other cases.