HarmonyOS 鸿蒙Next unicode编码如何转化utf-8字符串显示
HarmonyOS 鸿蒙Next unicode编码如何转化utf-8字符串显示
unicode编码如何转化utf-8字符串显示?
2 回复
let unicodeStr = "\u{1F468}\u200D\u{1F468}\u200D\u{1F467}\u200D\u{1F466}"
let textEncoder = new util.TextEncoder("utf-8");
let result = textEncoder.encodeInto(unicodeStr);
const str11 = buffer.from(result.buffer).toString()
console.info("unicodeStr11111:" + str11)
textEncoder文档如下:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V13/js-apis-util-V13#textencoder
可以把这一段代码贴出来吗?尤其是unicode字符串
看了您的代码,CN是传过来的unicode字符串,末尾就带了\u0000,所以字符串长度打印出来就是15。通过utf-8转码后,\u0000变成了\u0000\u0000。目前看,您应是想把末尾的\u0000都过滤掉?
这边写了一个过滤的方法,测试可行:
function stringToUint8Array(str: string) {
let uin8Arr = new Uint8Array(buffer.from(str,'utf-8').buffer);
let retUint8Arr:Array<number> = new Array()
for (let index = 0; index < uin8Arr.length; index++) {
const element = uin8Arr[index];
if (element != 0) {
retUint8Arr.push(element)
}
}
return new Uint8Array(retUint8Arr);
}
let unicodeStr = "\u0000测试_测试机构 林浩(副本1)\u0000"
console.info("unicodeStr:===" + unicodeStr + '===' + "==="+unicodeStr.length+"===")
let charStr = stringToUint8Array(unicodeStr)
console.info("charStr:" + charStr + '===== charStr.length:' + charStr.length)
let str222 = buffer.from(charStr.buffer).toString()
console.info("unicodeStr2222:" + str222 + '===== str222.length:' + str222.length)
let resultData222: ESObject = {
serialNumner:'123455678909988778123',
CN:str222
};
function stringToUint8Array(str: string) {
let uin8Arr = new Uint8Array(buffer.from(str,'utf-8').buffer);
console.debug('uin8Arr string:'+ uin8Arr.toString())
let retUint8Arr:Array<number> = new Array()
for (let index = 0; index < uin8Arr.length; index++) {
const element = uin8Arr[index];
if (element != 0) {
retUint8Arr.push(element)
}
}
return new Uint8Array(retUint8Arr);