从转义的ASCII序列中读取UTF8 / UNICODE字符

时间:2012-12-07 13:35:17

标签: c# .net unicode encoding utf-8

我在文件中有以下名称,我需要将字符串作为UTF8编码的字符串读取,所以从这个:

test_\303\246\303\270\303\245.txt

我需要获得以下内容:

test_æøå.txt

你知道如何使用C#实现这个目标吗?

1 个答案:

答案 0 :(得分:3)

假设你有这个字符串:

string input = "test_\\303\\246\\303\\270\\303\\245.txt";

即。字面意思

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

by“binary string”,我的意思是一个只包含代码点为0-255的字符的字符串。因此,这相当于一个穷人的byte[] 检索索引i处的字符代码点,而不是索引byte byte[]中的i值(这是我们几年前在javascript中所做的) 。因为iso-8859-1映射 确切地说,前256个unicode代码指向一个字节,非常适合将“二进制字符串”转换为byte[]

相关问题