自由色彩,无限魅力:www.zyml.net

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

上一篇 / 下一篇  2008-02-04 15:31:50

查看( 17 ) / 评论( 0 )
  
我们常做的一件事情,就是在文章系统中,截取一定长度的文章标题,超过指定长度,就加“...”
如两个字符串:
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

TAG:

我来说两句

(可选)

日历

« 2009-01-06  
    123
45678910
11121314151617
18192021222324
25262728293031

数据统计

  • 访问量: 104605
  • 日志数: 662
  • 图片数: 22
  • 影音数: 169
  • 商品数: 44
  • 文件数: 344
  • 书签数: 20
  • 建立时间: 2007-04-27
  • 更新时间: 2008-10-09

RSS订阅

Open Toolbar