C#实现 获取指定字节长度 中英文混合字符串 的方法

平时在作数据库插入操作时,如果用 INSERT 语句向一个varchar型字段插入内容时,有时会因为插入的内容长度超出规定的长度而报错。尤其是插入中英文混合字符串时,SQL Server中一般中文要占两个字节,所以对混合型的字符串就要作一个处理,统一按字节长度来计算字符串长度,方法如下:

/// <summary>

/// 获取指定字节长度的中英文混合字符串

/// </summary>

private string GetString(string str, int len)

{

string result = string.Empty;// 最终返回的结果

int byteLen = System.Text.Encoding.Default.GetByteCount(str);// 单字节字符长度

int charLen = str.Length;// 把字符平等对待时的字符串长度

int byteCount = 0;// 记录读取进度

int pos = 0;// 记录截取位置

if (byteLen > len)

{

for (int i = 0; i < charLen; i++)

{

if (Convert.ToInt32(str.ToCharArray()[i]) > 255)// 按中文字符计算加2

byteCount += 2;

else// 按英文字符计算加1

byteCount += 1;

if (byteCount > len)// 超出时只记下上一个有效位置

{

pos = i;

break;

}

else if(byteCount == len)// 记下当前位置

{

pos = i + 1;

break;

}

}

if(pos >= 0)

result = str.Substring(0, pos);

}

else

result = str;

return result;

}