用C#截取指定长度的中英文混合字符串

我们常做的一件事情,就是在文章系统中,截取一定长度的文章标题,超过指定长度,就加“...”

如两个字符串:

string str1 = "中国人要啊abc呀~";

string str2 = "1中国人23456abc呀~";

要截取后,输出:

str1 = "中国人要...";

str2 = "1中国人2...";

即要把中英文混合的字符串,在截取后,长度要一致,即8个字节的长度(不包括三个点),而且不能出现中文被从中间截断的情况。于是写了个方法:

public static string getStr(string s,int l)

{

string temp = s ;

if (Regex.Replace(temp,"[\u4e00-\u9fa5]","zz",RegexOptions.IgnoreCase).Length<=l)

{

return temp;

}

for (int i=temp.Length;i>=0;i--)

{

temp = temp.Substring(0,i);

if (Regex.Replace(temp,"[\u4e00-\u9fa5]","zz",RegexOptions.IgnoreCase).Length<=l-3)

{

return temp + "";

}

}

return "";

}

调用:

string content = "中国人啊abc呀呀呀呀";

content = getStr(content,13);

http://yao.cnblogs.com/archive/2006/07/04/442886.html

posted on 2008-08-19 15:37  草原和大树  阅读(345)  评论(0编辑  收藏  举报