Java 中的 ASCII 到 HTML 实体转义
我发现这个网站带有转义码,我只是想知道是否有人已经这样做了,这样我就不必花几个小时来构建这个逻辑:
StringBuffer sb = new StringBuffer();
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
switch (c) {
case '\u25CF': sb.append("●"); break;
case '\u25BA': sb.append("►"); break;
/*
... the rest of the hex chars literals to HTML entities
*/
default: sb.append(c); break;
}
}
I found this website with escape codes and I'm just wondering if someone has done this already so I don't have to spend couple of hours building this logic:
StringBuffer sb = new StringBuffer();
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
switch (c) {
case '\u25CF': sb.append("●"); break;
case '\u25BA': sb.append("►"); break;
/*
... the rest of the hex chars literals to HTML entities
*/
default: sb.append(c); break;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这些“代码”只是实际字符的 unicode 值的十进制表示形式。在我看来,这样的事情是可行的,除非你想非常严格地限制哪些代码被转换,哪些不被转换。
These "codes" is a mere decimal representation of the unicode value of the actual character. It seems to me that something like this would work, unless you want to be very strict about which codes get converted, and which don't.
其他答案对于代理对无法正常工作,例如,如果您有“
The other answers don't work correctly for surrogate pairs, e.g. if you have Emojis such as "????" (see character info). Here's how to do it in Java 8:
And for older Java:
A simple way to test if a solution handles surrogate pairs correctly is to use
"\uD83D\uDE00"
(????) as the input. If the output is"��"
, then it's wrong. The correct output is😀
.嗯,如果您这样做会怎么样:
然后您只需要确定您想要 HTML 转义的字符范围。在本例中,我只是指定了 ASCII 表空间之外的任何字符。
Hmm, what if you did something like this instead:
Then you just need to determine the range of characters you want HTML escaped. In this case I just specified any character beyond the ASCII table space.