DefaultHtmlStringify extends RawStringify { static public final String escape(String str) { if (str == null) { return str; } int size = str.length(); if (size == 0) { return str; } char c; String r; int lastPos = 0; StringBuilder sb = null; for (int pos = 0; pos < size; pos++) { c = str.charAt(pos); switch (c) { case '"': r = "&quot;"; break; case '\'': r = "&#39;"; break; case '&': r = "&amp;"; break; case '<': r = "&lt;"; break; case '>': r = "&gt;"; break; default: r = null; break; } if (r != null) { if (sb == null) { sb = new StringBuilder(size + r.length() - 1); } sb.append(str, lastPos, pos); sb.append(r); lastPos = pos + 1; } } if (sb == null) { return str; } if (lastPos < size) { sb.append(str, lastPos, size); } return sb.toString(); }  @Override String s(String str); @Override String s(Object obj); static final String escape(String str);  }
@Test public void escape() { DefaultHtmlStringify stringify = new DefaultHtmlStringify(); assertThat(stringify.s(null), is(nullValue())); assertThat(stringify.s(""), is("")); assertThat(stringify.s("&"), is("&amp;")); assertThat(stringify.s("a&b"), is("a&amp;b")); assertThat(stringify.s("ab"), is("ab")); assertThat(stringify.s("&b"), is("&amp;b")); assertThat(stringify.s("a&"), is("a&amp;")); assertThat(stringify.s("a&b<c>d'e\"f"), is("a&amp;b&lt;c&gt;d&#39;e&quot;f")); }