如何转换此字符串:
This string contains the Unicode character Pi(π)
转换为转义的ASCII字符串:
This string contains the Unicode character Pi(\u03a0)
和 反之亦然 ?
C#中当前可用的编码将π字符转换为“?”。我需要保留那个角色。
这往返于\ uXXXX格式。
class Program { static void Main( string[] args ) { string unicodeString = "This function contains a unicode character pi (\u03a0)"; Console.WriteLine( unicodeString ); string encoded = EncodeNonAsciiCharacters(unicodeString); Console.WriteLine( encoded ); string decoded = DecodeEncodedNonAsciiCharacters( encoded ); Console.WriteLine( decoded ); } static string EncodeNonAsciiCharacters( string value ) { StringBuilder sb = new StringBuilder(); foreach( char c in value ) { if( c > 127 ) { // This character is too big for ASCII string encodedValue = "\\u" + ((int) c).ToString( "x4" ); sb.Append( encodedValue ); } else { sb.Append( c ); } } return sb.ToString(); } static string DecodeEncodedNonAsciiCharacters( string value ) { return Regex.Replace( value, @"\\u(?<Value>[a-zA-Z0-9]{4})", m => { return ((char) int.Parse( m.Groups["Value"].Value, NumberStyles.HexNumber )).ToString(); } ); } }
输出:
此函数包含一个Unicode字符pi(π)
此函数包含一个Unicode字符pi(\ u03a0)