将字符串转换为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 = sop.getStringLength(str);
Console.WriteLine( " 字符串 " + str + " 的字节数为: " + iLen.ToString());
Console.ReadKey();
}
}
{
/// <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 = sop.getStringLength(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;
}
{
// 使用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;
int len = sarr.Length;