Unicode转成汉字 - 白牙的日志 - 努力哇!
Unicode转成汉字
rivate static List SplitByString(string source, string splitStr)
{
string input = source;
List final = new List();
int start = input.IndexOf(splitStr);
if (start > 0)
final.Add(input.Substring(0, start));
while (start < input.Length)
{
string unicode =input.Substring(start,6);
final.Add(unicode);
start += 6;
int end = input.IndexOf(splitStr,start);
if (end == -1)
end = input.Length;
if (start == end) //连续的
continue;
final.Add(input.Substring(start, end - start));
start += end - start;
}
return final;
}
public static string ConverTo(string sourceString)
{
List arrHexString = SplitByString(sourceString, "\\u");
StringBuilder resultString = new StringBuilder("");
foreach (string shexString in arrHexString)
{
if (shexString.Length == 6)
{
string hexString = shexString.Replace(@"\u", "");
string prexString = hexString.Substring(0, 2);
string suffixString = hexString.Substring(2);
byte prex = byte.Parse(prexString, System.Globalization.NumberStyles.AllowHexSpecifier);
byte suffix = byte.Parse(suffixString, System.Globalization.NumberStyles.AllowHexSpecifier);
byte[] unicodeBytes = { suffix, prex };
UnicodeEncoding encoding = new UnicodeEncoding();
resultString.Append(encoding.GetString(unicodeBytes));
}
else
{
resultString.Append(shexString);
}
}
return resultString.ToString();
{
string input = source;
List final = new List();
int start = input.IndexOf(splitStr);
if (start > 0)
final.Add(input.Substring(0, start));
while (start < input.Length)
{
string unicode =input.Substring(start,6);
final.Add(unicode);
start += 6;
int end = input.IndexOf(splitStr,start);
if (end == -1)
end = input.Length;
if (start == end) //连续的
continue;
final.Add(input.Substring(start, end - start));
start += end - start;
}
return final;
}
public static string ConverTo(string sourceString)
{
List arrHexString = SplitByString(sourceString, "\\u");
StringBuilder resultString = new StringBuilder("");
foreach (string shexString in arrHexString)
{
if (shexString.Length == 6)
{
string hexString = shexString.Replace(@"\u", "");
string prexString = hexString.Substring(0, 2);
string suffixString = hexString.Substring(2);
byte prex = byte.Parse(prexString, System.Globalization.NumberStyles.AllowHexSpecifier);
byte suffix = byte.Parse(suffixString, System.Globalization.NumberStyles.AllowHexSpecifier);
byte[] unicodeBytes = { suffix, prex };
UnicodeEncoding encoding = new UnicodeEncoding();
resultString.Append(encoding.GetString(unicodeBytes));
}
else
{
resultString.Append(shexString);
}
}
return resultString.ToString();
}
使用方法 string input = @”ilyu5357、lily\u6728\u5357lily”;
string output = ConverTo(input);
Console.WriteLine(output);