截取指定长度的字符串,区分汉字和字符
2009-01-20 15:13
609 查看
using System.Text;
using System.Text.RegularExpressions;
int current = 30;
int location_http = lblContext.Text.IndexOf("http");
int location_img = lblContext.Text.IndexOf("img");
if (location_http < current && location_http > 0)
{
current = location_http;
}
if (location_img < current && location_img > 0)
{
current = location_img;
}
lblContext.Text = GetFirstString(lblContext.Text, current);
public static string GetFirstString(string stringToSub, int length)
{
Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
char[] stringChar = stringToSub.ToCharArray();
StringBuilder sb = new StringBuilder();
int nLength = 0;
bool isCut = false;
for (int i = 0; i < stringChar.Length; i++)
{
if (regex.IsMatch((stringChar[i]).ToString()))
{
sb.Append(stringChar[i]);
nLength += 2;
}
else
{
sb.Append(stringChar[i]);
nLength = nLength + 1;
}
if (nLength >= length)
{
isCut = true;
break;
}
}
if (isCut)
return sb.ToString() + "..";
else
return sb.ToString();
}
using System.Text.RegularExpressions;
int current = 30;
int location_http = lblContext.Text.IndexOf("http");
int location_img = lblContext.Text.IndexOf("img");
if (location_http < current && location_http > 0)
{
current = location_http;
}
if (location_img < current && location_img > 0)
{
current = location_img;
}
lblContext.Text = GetFirstString(lblContext.Text, current);
public static string GetFirstString(string stringToSub, int length)
{
Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
char[] stringChar = stringToSub.ToCharArray();
StringBuilder sb = new StringBuilder();
int nLength = 0;
bool isCut = false;
for (int i = 0; i < stringChar.Length; i++)
{
if (regex.IsMatch((stringChar[i]).ToString()))
{
sb.Append(stringChar[i]);
nLength += 2;
}
else
{
sb.Append(stringChar[i]);
nLength = nLength + 1;
}
if (nLength >= length)
{
isCut = true;
break;
}
}
if (isCut)
return sb.ToString() + "..";
else
return sb.ToString();
}
相关文章推荐
- 截取指定长度的字符串,区分汉字和字符
- 从一个包含汉字和其他字符的字符串中截取指定字节长度的字符串,不可以出现中文乱码
- 截取指定长度的字符串(UTF-8专用 汉字和大写字母长度算1,其它字符长度算0.5)
- 不区分汉字还是英文和数字,按指定字节长度截取字符串
- 截取固定长度字符串显示在页面,多余部分显示为省略号(区分汉字和字符)
- 截取固定长度字符串显示在页面,多余部分显示为省略号(区分汉字和字符)
- 截取固定长度字符串显示在页面,多余部分显示为省略号(区分汉字和字符)
- 截取固定长度字符串显示在页面,多余部分显示为省略号(区分汉字和字符)
- 求中英文混合字符串长度,中英文混合字符串截取(汉字2个字节,字母数字等1个字节),字符转ASCII码,ASCII码转字符
- .net截取指定长度汉字超出部分以指定的字符代替
- 截取指定的字符长度(其中字符串中有中文,如果有半个中文则去掉)
- net截取指定长度汉字超出部分以指定的字符代替
- NSString:创建,长度,取字符,是否以某字符串开头,结尾, 查找指定字符串的范围,截取,拼接,替换,比较,替换,数值转换,大小写转换
- 截取指定长度的字符串(汉字不出现半个)
- js字符串长度计算(一个汉字==两个字符)和字符串截取
- 高效率的C#截取指定长度字符串,大于指定长度的,在末尾显示指定字符,默认为"..."
- .net截取指定长度汉字超出部分以指定的字符代替
- C#截取指定长度汉字超出部分以用指定的字符代替
- Java精确截取字符串/获取字符串前指定长度字符函数
- 区分全角和半角的字符串指定长度截取(或填充)