[英]How to convert String into HTML readable ASCII character
I am trying to convert Java String into HTML readable code.我正在尝试将 Java 字符串转换为 HTML 可读代码。
For Example: H ello W o r ld as H e l l o W o r l d
例如:你好 W o r ld as
H e l l o W o r l d
What I did so far:到目前为止我做了什么:
private static String convertToAscii(String str) {
for(int i=0; i<str.length(); i++) {
str += "&#"+(int)str.charAt(i);
}
return str;
}
its taking too much time plus processor fan making noice.它花费了太多时间加上处理器风扇制造噪音。
Thanks in advance提前致谢
This gif is not a perfect representation of what's happening here, but it gets the basic idea这个 gif 不是这里发生的事情的完美表示,但它得到了基本的想法
Over here...这边...
for(int i=0; i<str.length(); i++)
...You are looping through the String named str
. ...您正在遍历名为
str
的字符串。
But here...但在这儿...
str += ...
...You are adding to str. ...您正在添加到 str。
You are trying to get to the end of str, but you are literally adding to str for each loop.您正试图到达 str 的末尾,但实际上您是在为每个循环添加 str 。 You have created an infinite loop.
您已经创建了一个无限循环。
Add to a different String.添加到不同的字符串。 Like this.
像这样。
private static String convertToAscii(String str) {
String output = "";
for(int i=0; i<str.length(); i++) {
output += "&#"+(int)str.charAt(i);
}
return output;
}
You can also do something like that:你也可以这样做:
private static String convertToAscii(String str) {
return str
.chars()
.boxed()
.reduce("", (subRes, currVal) -> subRes + "&#" + currVal + ";" , (subVal, mappedVal) -> subVal + "" + mappedVal);
Its quicker with Java >= 8 Java >= 8 更快
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.