gpt4 book ai didi

java - 将包含 ASCII 的字符串转换为 Unicode

转载 作者:行者123 更新时间:2023-11-29 08:16:26 27 4
gpt4 key购买 nike

我从我的 HTML 页面获取一个字符串到我的 Java HTTPServlet 中。根据我的要求,我得到了显示汉字的 ASCII 代码:

"可以告诉我"(没有空格)

如何将此字符串转换为 Unicode?

HTML代码:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Find information</title>
<link rel="stylesheet" type="text/css" href="layout.css">
</head>
<body>

<form id="lookupform" name="lookupform" action="LookupServlet" method="post" accept-charset="UTF-8">
<table id="lookuptable" align="center">
<tr>
<label>Question:</label>
<td><textarea cols="30" rows="2" name="lookupstring" id="lookupstring"></textarea></td>
</tr>
</table>
<input type="submit" name="Look up" id="lookup" value="Look up"/>
</form>

Java代码:

request.setCharacterEncoding("UTF-8");
javax.servlet.http.HttpSession session = request.getSession();
LoginResult lr = (LoginResult) session.getAttribute("loginResult");
String[] question = request.getParameterValues("lookupstring");

如果我打印 question[0] 然后我得到这个值:“可以告诉我”

最佳答案

没有显示汉字的ASCII码。 ASCII 不代表汉字。

如果您已经有了一个 Java 字符串,它就已经有了所有字符(美国、拉丁、中文)的内部表示。然后,您可以使用 UTF-8 将该 Java 字符串编码为 Unicode。或 UTF-16交涉:

String s = "可以告诉我";(编辑:此行在没有汉字字体的系统上无法正确显示)

String s = "\u53ef\u4ee5\u544a\u8bc9\u6211";
byte utfString = s.getBytes("UTF-8");

现在我查看了您更新的问题,您可能正在寻找 StringEscapeUtils类(class)。它来自 Apache Commons Text。并且会将您的 HTML 实体转义为 Java 字符串:

String s = StringEscapeUtils.unescapeHtml("& #21487;& #20197;& #21578;& #35785;& #25105;"); // without spaces

关于java - 将包含 ASCII 的字符串转换为 Unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4526192/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com