C#截取中英文混合指定长度字符串实例
using system.text.regularexpressions;
using system.text;
/// <summary>
/// 字符串长度(按字节算)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static int strlength(string str)
{
int len = 0;
byte[] b;
for (int i = 0; i < str.length; i++)
{
b = encoding.default.getbytes(str.substring(i,1));
if (b.length > 1)
len += 2;
else
len++;
}
return len;
}
/// <summary>
/// 截取指定长度字符串(按字节算)
/// </summary>
/// <param name="str"></param>
/// <param name="length"></param>
/// <returns></returns>
static string strcut(string str, int length)
{
int len = 0;
byte[] b;
stringbuilder sb = new stringbuilder();
for (int i = 0; i < str.length; i++)
{
b = encoding.default.getbytes(str.substring(i, 1));
if (b.length > 1)
len += 2;
else
len++;
if (len >= length)
break;
sb.append(str[i]);
}
return sb.tostring();
}
上一篇: 查看Java所支持的语言及相应的版本信息
下一篇: Java实现文件点击没反应的方法