现在的位置: 首页 > 综合 > 正文

c# stream byte char string 流、字节、字符、字符串

2013年02月22日 ⁄ 综合 ⁄ 共 2297字 ⁄ 字号 评论关闭

1、两种不同的方法计算字符串的长度

        string strTmp = "wk986王克东";
           
        int i = System.Text.Encoding.Default.GetBytes(strTmp).Length;    //算汉字的长度
        int j = strTmp.Length;                                                                     //不算汉字的长度

        Console.WriteLine("字符串{0},算汉字的长度:{1},不算汉字长度:{2}",     strTmp,i,j);

        //转换成数组计算数组的长度

        byte[] bytStr = System.Text.Encoding.Default.GetBytes(strTmp);   
        int len = bytStr.Length;
        Console.WriteLine("字符串长度:"+len.ToString());
        Console.Read();

 

2、System.Text.StringBuilder("")

       和字符串“+”是不一样的,在C#中,字符串是“引用”类型,每加一个是重新建立了一个字符串,当字符串特别大的时候,性能消耗大,所以要用StringBuilder。

         System.Text.StringBuilder sb = new System.Text.StringBuilder(""); 
         sb.Append("中华"); 
         sb.Append("人民"); 
         sb.Append("共和国");
         Console.WriteLine(sb);

//判断汉字个数

private int ChkGBKLen(string str)
{
System.Text.ASCIIEncoding n = new System.Text.ASCIIEncoding();
    byte[] b = n.GetBytes(str);
    int l = 0;
    for (int i = 0; i <= b.Length - 1; i++)
    {
     if (b[i] == 63) //判断是否为汉字或全脚符号
        {
            l++;
        }
    }
    return l;
}

C#中流,字节,字符,字符串
2010-04-19 23:01

首先要明白它们本身是由什么组成的:

流:二进制

字节:无符号整数

字符:Unicode编码字符

字符串:多个Unicode编码字符

那么在.net下它们之间如何转化呢?

一般是遵守以下规则:

流->字节数组->字符数组->字符串

下面就来具体谈谈转化的语法:

流->字节数组

MemoryStream ms = new MemoryStream();

byte[] buffer = new byte[ms.Length];

ms.Read(buffer, 0, (int)ms.Length);

字节数组->流

byte[] buffer = new byte[10];

MemoryStream ms = new MemoryStream(buffer);

字节数组->字符数组

1.

byte[] buffer = new byte[10];

char[] ch = new ASCIIEncoding().GetChars(buffer);

//或者:char[] ch = Encoding.UTF8.GetChars(buffer)

2.

byte[] buffer = new byte[10];

char[] ch = new char[10];

for(int i=0; i<buffer.Length; i++)

{

    ch[i] = Convert.ToChar(buffer[i]);

}

字符数组->字节数组

1.

char[] ch = new char[10];

byte[] buffer = new ASCIIEncoding().GetBytes(ch);

//或者:byte[] buffer = Encoding.UTF8.GetBytes(ch)

2.

char[] ch = new char[10];

byte[] buffer = new byte[10];

for(int i=0; i<ch.Length; i++)

{

    buffer[i] = Convert.ToByte(ch[i]);

}

字符数组->字符串

char[] ch = new char[10];

string str = new string(ch);

字符串->字符数组

string str = "abcde";

char[] ch=str .ToCharArray();

字节数组->字符串

byte[] buffer = new byte[10];

string str = System.Text.Encoding.UTF8.GetString(buffer);

//或者:string str = new ASCIIEncoding().GetString(buffer);

字符串->字节数组

string str = "abcde";

byte[] buffer=System.Text.Encoding.UTF8.GetBytes(str);

//或者:byte[] buffer= new ASCIIEncoding().GetBytes(str);

说明:主要就是用到了Convert类和System.Text命名空间下的类,Encoding是静态类,ASCIIEncoding是实体类,方法都是一样的!

【上篇】
【下篇】

抱歉!评论已关闭.