C# string 转换为 UTF-8

private string Convert(String str) 
{
 char[] hexDigits = {         '0', '1', '2', '3', '4', '5', '6', '7','8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

 Encoding utf8 = Encoding.UTF8;

 StringBuilder result = new StringBuilder();

 for (int i=0;i  {
  string sub = str.Substring(i,1);
  byte[] bytes = utf8.GetBytes(sub);

  if (bytes.Length == 1) //普通英文字母或数字
  {
   result.Append(sub);
  }
  else  //其它字符,转换成为编码
  {
   for (int j=0;j    {
    result.Append("%"+hexDigits[bytes[j]>>4]+hexDigits[bytes[j] & 0XF]);
   }
  }
 }

 return result.ToString();
}

你可能感兴趣的:(C#,string,c#,encoding,byte,c)