一个字符串长度处理的方法。(判断字符串中某位置是不是中文字符)
做项目遇到了一个小问题。产品表中Memo列在数据库中定义的VARCHAR(50)。在使用GirdView编辑更新时,如果输入的字符串字节长度超过50了会出现“将截断字符串或二进制数据” 的错误。 但是又不能简单的限制文本框的长度,因为中文占2个字节。所以串的字节长度是不定的。这个时候就要根据串的字节长度来截取了。代码如下:
/// <summary>
/// 计算字符串的字节长度,处理含有中文的字符串写入SQLServer过长。
/// </summary>
/// <param name="str">要处理的字符串</param>
/// <param name="len">截取的字节长度</param>
/// <returns></returns>
static public string GIsHalfHZ(string str, int len)
{
int numLen = 0;
string _temp = "";
for (int i = 0; i < str.Length; i++)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
numLen += System.Text.Encoding.Default.GetByteCount(str.Substring(i, 1));
if (numLen <= len)
_temp += str.Substring(i, 1);
}
return _temp;
}
刚做程序不久,有不对的地方请给为指出来!
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
刚做程序不久,有不对的地方请给为指出来!