replaceAll
should be able to do the job just fine.
First, let's make a quick tuple class to represent a pair of Strings: the string to search for and the string to replace that with:
private static class StringTuple{
private String k;
private String v;
public StringTuple(String one, String two){
k = one;
v = two;
}
}
With that, we can build a list of special characters to search for and their corresponding replacements. Note that this list is going to be used in the order that we create it, so it's important that we replace special characters that might show up in other replacements first (such as &
or ;
).
ArrayList<StringTuple> specialChars = new ArrayList<>();
specialChars.add(new StringTuple("&", "&"));
specialChars.add(new StringTuple("<", "<"));
specialChars.add(new StringTuple(">", ">"));
Finally, we can write a function that loops over the list of special chars and replaces all occurrences with the replacement string:
public static String replaceSpecialChars(String s, ArrayList<StringTuple> specialChars){
for(StringTuple e: specialChars){
s = s.replaceAll(e.k, e.v);
}
return s;
}
Here's a runnable main based off of the above code:
public static void main(String[] args) {
ArrayList<StringTuple> specialChars = new ArrayList<>();
specialChars.add(new StringTuple("&", "&"));
specialChars.add(new StringTuple("<", "<"));
specialChars.add(new StringTuple(">", ">"));
System.out.println(replaceSpecialChars("Hi <Nishanth> How are &you !", specialChars));
}
Output: Hi <Nishanth> How are &you !