unicode to gb2312 转换

  用reflector 反编译出来的代码中,中文变成乱糟糟的unicode,害我看得吃力啊!我只好把它们变过来喽!

用了下面一点代码,有我自己写的字符串分割方法,unicode to gb2312的转换函数。方法笨了点,但管用。

/// <summary>
  /// 将字符串分割成数组
  /// </summary>
  /// <param name="strSource"></param>
  /// <param name="strSplit"></param>
  /// <returns></returns>
  public string[] StringSplit(string strSource,string strSplit)
  {
   string[] strtmp = new string[1];
   int index = strSource.IndexOf(strSplit,0);
   if(index<0)
   {
    strtmp[0] = strSource;
    return strtmp;
   }
   else
   {
    strtmp[0] = strSource.Substring(0,index);
    return StringSplit(strSource.Substring(index+strSplit.Length),strSplit,strtmp);
   }
  }

  /// <summary>
  /// 采用递归将字符串分割成数组
  /// </summary>
  /// <param name="strSource"></param>
  /// <param name="strSplit"></param>
  /// <param name="attachArray"></param>
  /// <returns></returns>
  private string[] StringSplit(string strSource,string strSplit,string[] attachArray)
  {
   string[] strtmp = new string[attachArray.Length+1];
   attachArray.CopyTo(strtmp,0);

   int index = strSource.IndexOf(strSplit,0);
   if(index<0)
   {
    strtmp[attachArray.Length] = strSource;
    return strtmp;
   }
   else
   {
    strtmp[attachArray.Length] = strSource.Substring(0,index);
    return StringSplit(strSource.Substring(index+strSplit.Length),strSplit,strtmp);
   }   
  }

  /// <summary>
  /// 将Unicode转化为GB2312
  /// </summary>
  /// <param name="str"></param>
  /// <returns></returns>
  public string ConvertToGb2312(string str)
  {
   bool flag = false;
   string tmpSubString = string.Empty;
   string[] strArray = StringSplit(str,@"/u");

   char[] charArray = new char[strArray.Length];
   string ret=string.Empty;
   for(int i=0;i < strArray.Length;i++)
   {
    if(strArray[i].Length==0)
     continue;
    if(StringLength(strArray[i]) == 4 && strArray[i].Length == 4 && strArray[i].ToLower() == strArray[i])
    {
     try
     {
      charArray[i] = System.Convert.ToChar(System.Convert.ToInt32(strArray[i],16));
      ret += charArray[i].ToString();
      flag = true;
     }
     catch
     {
      ret += strArray[i];
      flag = false;
     }
    }
    else
    {
     if(flag && strArray[i].ToLower() == strArray[i])
     {
      try
      {
       tmpSubString = strArray[i].Substring(4);
       charArray[i] = System.Convert.ToChar(System.Convert.ToInt32(strArray[i].Substring(0,4),16));
       ret += charArray[i].ToString() + tmpSubString;
      }
      catch
      {
       ret += strArray[i];
      }
     }
     else
     {   
      ret += strArray[i];
     }
     flag = false;
    }
   }
   return ret;
  }

  public int StringLength(string str)
  {
   byte[] strArray=System.Text.Encoding.Default.GetBytes (str);
   int res=strArray.Length ;
   return res;
  }

阅读更多
文章标签: string byte
个人分类: C#
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭