获取字符串长度

string str = “ABCDadcf测试”;
int l = str.Length;

 

获取字符串字节长度

public int ByteLength(string str)
        {
            //使用Unicode编码的方式将字符串转换为字节数组,它将所有字符串(包括英文中文)全部以2个字节存储
            byte[] bytestr = System.Text.Encoding.Unicode.GetBytes(str);
            int j = 0;
            for (int i = 0; i < bytestr.GetLength(0); i++)
            {
                //取余2是因为字节数组中所有的双数下标的元素都是unicode字符的第一个字节
                if (i % 2 == 0)
                {
                    j++;
                }
                else
                {
                    //单数下标都是字符的第2个字节,如果一个字符第2个字节为0,则代表该Unicode字符是英文字符,否则为中文字符
                    if (bytestr[i] > 0)
                    {
                        j++;
                    }
                }
            }
            return j;
        }