C#字符串操作步骤

在C#字符串中,System.String类是一个引用类型,但与其他引用类型不同的是,将C#字符串视为一个基本类型:可以声明为一个常量,并可以直接赋值。这里将介绍操作步骤。

操作步骤代码:

 
 
 
  1. //获得汉字的区位码  
  2. byte[] array = new byte[2];  
  3. array = System.Text.Encoding.Default.GetBytes("啊");  
  4.  
  5.  
  6.  
  7. int i1 = (short)(array[0] - ''\0'');  
  8. int i2 = (short)(array[1] - ''\0'');  
  9.  
  10.  
  11. //unicode解码方式下的汉字码  
  12. array = System.Text.Encoding.Unicode.GetBytes("啊");  
  13. i1 = (short)(array[0] - ''\0'');  
  14. i2 = (short)(array[1] - ''\0'');  
  15.  
  16.  
  17. //unicode反解码为汉字  
  18. string str = "4a55";  
  19. string s1 = str.Substring(0,2);  
  20. string s2 = str.Substring(2,2);  
  21.  
  22.  
  23. int t1 = Convert.ToInt32(s1,16);  
  24. int t2 = Convert.ToInt32(s2,16);  
  25.  
  26.  
  27. array[0] = (byte)t1;  
  28. array[1] = (byte)t2;  
  29.  
  30.  
  31. string s = System.Text.Encoding.Unicode.GetString(array);  
  32.  
  33.  
  34. //default方式反解码为汉字  
  35. array[0] = (byte)196;  
  36. array[1] = (byte)207;  
  37. s = System.Text.Encoding.Default.GetString(array);  
  38.  
  39.  
  40. //取字符串长度  
  41. s = "iam方枪枪";  
  42. int len = s.Length;//will output as 6  
  43. byte[] sarr = System.Text.Encoding.Default.GetBytes(s);  
  44. len = sarr.Length;//will output as 3+3*2=9 
  45.  
  46.  
  47. //字符串相加  
  48. System.Text.StringBuilder sb = new System.Text.StringBuilder("");  
  49. sb.Append("i ");  
  50. sb.Append("am ");  
  51. sb.Append("方枪枪");  
  52.  
  53. string --> byte array  
  54. byte[] data=Syste.Text.Encoding.ASCII.GetBytes(string);  
  55. string --> byte  
  56. byte data = Convert.ToByte(string);  
  57. byte[]-->string  
  58. string string = Encoding.ASCII.GetString( bytes, 0, nBytesSize ); 

以上介绍C#字符串操作步骤

【编辑推荐】

  1. C#编写数字转换中文算法
  2. 分析C#调用COM对象
  3. C# SingleInstance类浅析
  4. 概述C#调用Active组件
  5. C# Convert.ToInt32简介
THE END