项目中需要将前端传过来的特殊字符做转义处理,然后在保存到数据库中,比如说“<”,">",但是替换一直失败
先看错误的做法:(不能达到替换效果)
public class StringTest { public static void main(String[] arg){ String s = "0<R<=150"; if (s.contains("<=")) { s.replace("<=", "≤"); System.out.println("1s=" + s); } } }
输出:1s=0<R<=150
正确的做法:(达到替换效果)
public class StringTest { public static void main(String[] arg){ String s = "0<R<=150"; if (s.contains("<=")) { s = s.replace("<=", "≤");//必须要重新赋值给一个字符串 System.out.println("1s=" + s); } }}
输出:1s=0<R≤150
原因见api:
replace public String replace(char oldChar, char newChar) 返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。 如果 oldChar 在此 String 对象表示的字符序列中没有出现,则返回对此 String 对象的引用。否则,创建一个新的 String 对象,它所表示的字符序列除了所有的 oldChar 都被替换为 newChar 之外,与此 String 对象表示的字符序列相同。 示例: "mesquite in your cellar".replace('e', 'o') returns "mosquito in your collar" "the war of baronets".replace('r', 'y') returns "the way of bayonets" "sparring with a purple porpoise".replace('p', 't') returns "starring with a turtle tortoise" "JonL".replace('q', 'x') returns "JonL" (no change) 参数: oldChar - 原字符。 newChar - 新字符。 返回: 一个从此字符串派生的字符串,它将此字符串中的所有 oldChar 替代为 newChar。
附 HTML特殊字符编码大全:
要替换好多特殊字符了!