C#获取字符串字节的长度
/// <summary>
/// 获取字符串字节长度
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static int StringToByteLength(string str)
{
//使⽤Unicode编码的⽅式将字符串转换为字节数组,它将所有字符串(包括英⽂中⽂)全部以2个字节存储
byte[] bytestr = System.Text.Encoding.UTF8.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;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。