我的文件中有以下名称,我需要将该字符串读取为 UTF8 编码的字符串,因此:
test_\303\246\303\270\303\245.txt
我需要获得以下信息:
test_æøå.txt
你知道如何使用 C# 来实现这一点吗?
假设你有这个字符串:
string input = "test_\\303\\246\\303\\270\\303\\245.txt";
IE。字面上地
test_\303\246\303\270\303\245.txt
你可以这样做:
string input = "test_\\303\\246\\303\\270\\303\\245.txt";
Encoding iso88591 = Encoding.GetEncoding(28591); //See note at the end of answer
Encoding utf8 = Encoding.UTF8;
//Turn the octal escape sequences into characters having codepoints 0-255
//this results in a "binary string"
string binaryString = Regex.Replace(input, @"\\(?<num>[0-7]{3})", delegate(Match m)
{
String oct = m.Groups["num"].ToString();
return Char.ConvertFromUtf32(Convert.ToInt32(oct, 8));
});
//Turn the "binary string" into bytes
byte[] raw = iso88591.GetBytes(binaryString);
//Read the bytes into C# string
string output = utf8.GetString(raw);
Console.WriteLine(output);
//test_æøå.txt
我所说的“二进制字符串”是指仅由代码点为 0-255 的字符组成的字符串。因此,这相当于一个穷人的byte[]
在哪里
您检索索引处字符的代码点i
, 代替byte
值在一个byte[]
在索引处i
(这就是我们几年前在 javascript 中所做的)。因为 iso-8859-1 映射
恰好前 256 个 unicode 代码指向单个字节,它非常适合将“二进制字符串”转换为byte[]
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)