C#中的編碼轉化
在轉化之前,必須要先知道當前變量的編碼.對於.NET下的string永远是Unicode的. 對於從文本文件中讀取的byte[]或string的編碼,也可以通過判斷文件的編碼來確定.詳細判斷方法見另一篇文章.
下面介紹在已知當前孌量的情況下的轉化:
Encoding utf8 = Encoding.UTF8;
Encoding gb2312 = Encoding.GetEncoding("gb2312");
1.字符串的轉化
--1.字符串-->>相同編碼字節數組
例1: 將utf8字符串轉化為utf8字節數組
byte[] utf8Bytes = utf8.GetBytes(utf8string);
例2: 將unicode字符串轉化為unicode字節數組
byte[] gb2312Bytes= System.Text.Encoding.GetEncoding("gb2312").GetBytes("Unicode汉字");
--2.字符串-->>另一編碼字符串
方法:字符串-->字節數組-->另一編碼字節數組-->另一編碼字符串.
--3.字符串-->>字符数组
char[] c = inputString.ToCharArray();
2.字節數組的轉化
--1.字節數組--->>相同編碼字符串
string result = System.Text.Encoding.GetEncoding( " gb2312 " ).GetString(gb2312Bytes, 0 ,gb2312Bytes.Length);
--2.字節數組-->>另一編碼字節數組
//例1:將utf8字節數組轉化為gb2312字節數組
byte[] asciiBytes = Encoding.Convert(utf8, gb2312, utf8Bytes);
--3.字節數組-->>相同編碼字符數組.
//例1:將gb2312字節數組轉化為gb2312字符數組
char[] asciiChars = new char[gb2312.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
gb2312.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
3.字符數組的轉化
--1.字符數組-->>相同編碼字節數組
gb2312string = new string(asciiChars);
String.substring(0, n)函数返回该字符串前n个字符的新字符串,但如果只想返回前n个字节,而字符串中又含有中文等双字节字符怎么办呢,我写了个函数,不过只假定参数字符串中只含有单字节和双字节字符,不包含4字节的Unicode32。
例如:"我ABC是中国人DEF",截取5个字节应返回"我ABC",截取6个字节应返回"我ABC",截取7个字节应返回"我ABC是"。
{
try
{
byte [] array = input.getBytes( " GBK " );
if ( bytes >= array.length ) return input;
String result = new String(array , 0 , bytes , " GBK " );
return result.length() > 0 ? result : new String(array , 0 , bytes - 1 , " GBK " );
}
catch (UnsupportedEncodingException e)
{
return input;
}
}