[英]Read UTF8/UNICODE characters from an escaped ASCII sequence
我在文件中使用以下名稱,我需要將字符串讀取為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[]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.