C# UTF-8 字符串中的字节位置
C# UTF-8 Byte position in a String
我有一个外部 3.party 库,它对字符串进行分析,returns 给定字符串中有趣的列表 things/events。
我的问题是 3.party 库 returns 找到的位置是字节位置,而不是字符串位置,当我将字符串传递给 3.party 时,我将其作为 UTF-8 传递使用 Encoding.UTF8.GetBytes(text) 对 byte[] 进行编码,因此将 returns 作为字节位置确实有意义。
因为UTF-8中的一个字符没有固定的大小,所以不能直接翻译成String位置。
问题是:
"I am your father" "your" 位于字节位置 5,长度为 4
"我是你的父亲" "yøur" 在字节位置 5 处找到,长度为 5
"I am your father" "father" 位于字节位置 10,长度为 6
"I am your father" "father" 在字节位置 11 处找到,长度为 6
我的问题是,如何将字节位置转换为字符串位置?
它是 O(n),所以它很糟糕但是:
string str = "I am yøur father";
byte[] utf8 = Encoding.UTF8.GetBytes(str);
int len;
int ix = YourMethod(utf8, out len);
int ix2 = Encoding.UTF8.GetCharCount(utf8, 0, ix);
int len2 = Encoding.UTF8.GetCharCount(utf8, ix, len);
ix2
和 len2
在 .NET char
中。
请注意,您可以进行简单的优化:
int ix2;
int len2;
if (str.Length != utf8.Length)
{
ix2 = Encoding.UTF8.GetCharCount(utf8, 0, ix);
len2 = Encoding.UTF8.GetCharCount(utf8, ix, len);
}
else
{
ix2 = ix;
len2 = len;
}
我有一个外部 3.party 库,它对字符串进行分析,returns 给定字符串中有趣的列表 things/events。
我的问题是 3.party 库 returns 找到的位置是字节位置,而不是字符串位置,当我将字符串传递给 3.party 时,我将其作为 UTF-8 传递使用 Encoding.UTF8.GetBytes(text) 对 byte[] 进行编码,因此将 returns 作为字节位置确实有意义。
因为UTF-8中的一个字符没有固定的大小,所以不能直接翻译成String位置。
问题是:
"I am your father" "your" 位于字节位置 5,长度为 4
"我是你的父亲" "yøur" 在字节位置 5 处找到,长度为 5
"I am your father" "father" 位于字节位置 10,长度为 6
"I am your father" "father" 在字节位置 11 处找到,长度为 6
我的问题是,如何将字节位置转换为字符串位置?
它是 O(n),所以它很糟糕但是:
string str = "I am yøur father";
byte[] utf8 = Encoding.UTF8.GetBytes(str);
int len;
int ix = YourMethod(utf8, out len);
int ix2 = Encoding.UTF8.GetCharCount(utf8, 0, ix);
int len2 = Encoding.UTF8.GetCharCount(utf8, ix, len);
ix2
和 len2
在 .NET char
中。
请注意,您可以进行简单的优化:
int ix2;
int len2;
if (str.Length != utf8.Length)
{
ix2 = Encoding.UTF8.GetCharCount(utf8, 0, ix);
len2 = Encoding.UTF8.GetCharCount(utf8, ix, len);
}
else
{
ix2 = ix;
len2 = len;
}