简体   繁体   中英

encoding special characters in java

I have a string message to display which contains special characters but it doesnt print all. For example if I give message like "The P & A company does the work". It prints only "The P".

public void setOutageMsg(String outageMsg) {
        //outage msg issue
        if(outageMsg==null){
            this.outageMsg = outageMsg;
        }
        else{
            outageMsg=outageMsg.replaceAll("&","&").replaceAll("&","%26");  
            this.outageMsg = outageMsg;
        }
    }

Similarly, I need to have a single code for all the special characters.

Try this, It may help you

outageMsg=outageMsg.replaceAll("&","&").replaceAll("&","\u0026");

or

outageMsg=outageMsg.replaceAll("&(?!amp;)","&").replaceAll("&","\u0026"); 

You can write something along these lines

    public void setOutageMsg(String outageMsg) {
            //outage msg issue
            if(outageMsg==null){
                this.outageMsg = outageMsg;
            }
            else{
                this.outageMsg = getFormattedString(outageMsg);
            }
        }

    private String getFormattedString(String outageMsg){
           outageMsg.replaceAll("&","&");
           outageMsg.replaceAll("a","b");
           //...
           return outageMsg;
       }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM