0

I have a String with special characters which I want to be replaced by corresponding reference.

For example

InputString -> Hi <Nishanth> How &are you !
OutputString -> Hi &ltNishanth&gt How &ampare you &excl

I tried using concept of replace. But I couldn't achieve the desired result .. I want a function which would do it for me in Java.

Michael
  • 32,527
  • 49
  • 210
  • 370

1 Answers1

0

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("&", "&amp;"));
specialChars.add(new StringTuple("<", "&lt;"));
specialChars.add(new StringTuple(">", "&gt;"));

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("&", "&amp;"));
    specialChars.add(new StringTuple("<", "&lt;"));
    specialChars.add(new StringTuple(">", "&gt;"));
    System.out.println(replaceSpecialChars("Hi <Nishanth> How are &you !", specialChars));
}

Output: Hi &lt;Nishanth&gt; How are &amp;you !

Mshnik
  • 7,032
  • 1
  • 25
  • 38