c#获取字符串的字节数的⽅法
将字符串转换为ASCII编码数组,只要是中⽂字节码就是ASCII编码63即"?",所以可以由此来进⾏判断
复制代码代码如下:
class StringOP
{
/// <summary>
/// 获取中英⽂混排字符串的实际长度(字节数)
/// </summary>
/// <param name="str">要获取长度的字符串</param>
/// <returns>字符串的实际长度值(字节数)</returns>
public int getStringLength(string str)
{
if (str.Equals(string.Empty))
return 0;
int strlen = 0;
ASCIIEncoding strData = new ASCIIEncoding();
//将字符串转换为ASCII编码的字节数字
byte[] strBytes = strData.GetBytes(str);
for (int i = 0; i <= strBytes.Length - 1; i++)
{
if (strBytes[i] == 63)  //中⽂都将编码为ASCII编码63,即"?"号
strlen++;
strlen++;
}
return strlen;
}
}
class TestMain
{
static void Main()
{
字符串转数组编码方式
StringOP sop = new StringOP();
string str = "I Love China!I Love 北京!";
int iLen = StringLength(str);
Console.WriteLine("字符串" + str + "的字节数为:" + iLen.ToString());
Console.ReadKey();
}
}
将字符串以Unicode的编码转换为字节数组,判断每个字符的第⼆个字节是否⼤于0,来计算字符串的字节数
复制代码代码如下:
public static int bytelenght(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;
}
直接转成字节码获取长度:
复制代码代码如下:
byte[] sarr = System.Text.Encoding.Default.GetBytes(s);    int len = sarr.Length;

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