gpt4 book ai didi

c# - 如何将utf8字节数组转换为给定长度的字符串

转载 作者:行者123 更新时间:2023-11-30 21:37:20 26 4
gpt4 key购买 nike

假设我有一个字节数组:

var myArr = new byte[] { 0x61, 0x62, 0xc4, 0x85, 0xc4, 0x87 };

所以它有 6 个元素,而它对应于 utf8 abąć 有 4 个字母。通常你会这样做

Encoding.UTF8.GetString(myArr);

将其转换为字符串。但是让我们假设 myArr 实际上更大(末尾有更多字节)但我知道(先验转换)我只想要前 4 个字母。如何高效地将这个数组转换为字符串?此外,最好在 myArr 数组中包含最后一个字节的索引(对应于转换后的字符串的末尾)。

例子:

// 3 more bytes at the end of formerly defined myArr
var myArr = new byte[] { 0x61, 0x62, 0xc4, 0x85, 0xc4, 0x87, 0x01, 0x02, 0x03 };
var str = MyConvert(myArr, 4); // read 4 utf8 letters
// str is "abąć"
// possibly I want to know that MyConvert stoped at the index 6 in myArr

生成的 string str 对象应该有 str.Length == 4

最佳答案

看起来像Decoder有你的支持,特别是有点巨大的Convert方法。我想你会想要:

var decoder = Encoding.UTF8.GetDecoder();
var chars = new char[4];
decoder.Convert(bytes, 0, bytes.Length, chars, 0, chars.Length,
true, out int bytesUsed, out int charsUsed, out bool completed);

使用问题中的数据完成示例:

using System;
using System.Text;

public class Test
{
static void Main()
{
var bytes = new byte[] { 0x61, 0x62, 0xc4, 0x85, 0xc4, 0x87, 0x01, 0x02, 0x03 };
var decoder = Encoding.UTF8.GetDecoder();
var chars = new char[4];
decoder.Convert(bytes, 0, bytes.Length, chars, 0, chars.Length,
true, out int bytesUsed, out int charsUsed, out bool completed);
Console.WriteLine($"Completed: {completed}");
Console.WriteLine($"Bytes used: {bytesUsed}");
Console.WriteLine($"Chars used: {charsUsed}");
Console.WriteLine($"Text: {new string(chars, 0, charsUsed)}");
}
}

关于c# - 如何将utf8字节数组转换为给定长度的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47352465/

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