如何将此字符串解码为utf-8字符串

本文关键字:字符串 解码 utf-8 | 更新日期: 2023-09-27 18:07:30

我有这样的代码:

string URL = "http://translate.google.com/m?hl=vi&sl=en&tl=vi&ie=UTF-8&prev=_m&q=song";
string s = "";
WebClient client = new WebClient();
client.Headers.Add("user-agent", "Mozilla/5.0 (SymbianOS/9.4; U; Series60/5.0 Nokia5800d-1/21.0.025; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413");
s = client.DownloadString(URL);

运行时,我收到一个字符串,格式如下:

danh tÆ°Ì€ buổi há»p để ca hát

:

danh từ buổi họp để ca hát

如何将此字符串解码为utf-8字符串

当获得一个表示字符串的byte[]时,您需要在获得它之前知道使用了什么编码。

在这种情况下,它是UTF-8,所以将WebClientEncoding设置为会得到正确的字符串:

string URL = "http://translate.google.com/m?hl=vi&sl=en&tl=vi&ie=UTF-8&prev=_m&q=song";
string s = "";
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
client.Headers.Add("user-agent", "Mozilla/5.0 (SymbianOS/9.4; U; Series60/5.0 Nokia5800d-1/21.0.025; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413");
s = client.DownloadString(URL);