如何将Unicode编码的字符串转换为字母字符串 [英] How to convert a string with Unicode encoding to a string of letters

查看:55
本文介绍了如何将Unicode编码的字符串转换为字母字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有转义 Unicode 字符的字符串,uXXXX, 我想把它转换成普通的 Unicode 字母.例如:

I have a string with escaped Unicode characters, uXXXX, and I want to convert it to regular Unicode letters. For example:

"u0048u0065u006Cu006Cu006F World"

应该变成

"Hello World"

我知道当我打印第一个字符串时,它已经显示了 Hello world.我的问题是我从文件中读取文件名,然后搜索它们.文件中的文件名用 Unicode 编码进行了转义,当我搜索文件时,我找不到它们,因为它搜索名称中带有 uXXXX 的文件.

I know that when I print the first string it already shows Hello world. My problem is I read file names from a file, and then I search for them. The files names in the file are escaped with Unicode encoding, and when I search for the files, I can't find them, since it searches for a file with uXXXX in its name.

推荐答案

技术上做:

String myString = "u0048u0065u006Cu006Cu006F World";

自动将其转换为 "Hello World",因此我假设您正在从某个文件中读取字符串.为了将其转换为Hello",您必须将文本解析为单独的 unicode 数字,(获取 uXXXX 并获取 XXXX)然后执行 Integer.ParseInt(XXXX, 16) 获得一个十六进制值,然后将其转换为 char 以获得实际字符.

automatically converts it to "Hello World", so I assume you are reading in the string from some file. In order to convert it to "Hello" you'll have to parse the text into the separate unicode digits, (take the uXXXX and just get XXXX) then do Integer.ParseInt(XXXX, 16) to get a hex value and then case that to char to get the actual character.

完成此操作的一些代码:

String str = myString.split(" ")[0];
str = str.replace("\","");
String[] arr = str.split("u");
String text = "";
for(int i = 1; i < arr.length; i++){
    int hexVal = Integer.parseInt(arr[i], 16);
    text += (char)hexVal;
}
// Text will now have Hello

这篇关于如何将Unicode编码的字符串转换为字母字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆