zoukankan      html  css  js  c++  java
  • 用C#截取指定长度的中英文混合字符串

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

    如两个字符串:
    string str1 = "中国人要啊abc呀~";
    string str2 = "1中国人23456abc呀~";

    要截取后,输出:

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

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

    using System.Text.RegularExpressions;

    //
    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);

    2008-03-06:
    用C#截取指定长度的中英文混合字符串 改进版>>

  • 相关阅读:
    Oracle And子句
    Oracle Where(条件)子句用法
    extern “C”的作用详解
    函数重载
    给变量起名字的网站。
    同步异步
    CCS5.5安装破解过程
    Semaphore_pend();阻塞函数
    vi常用命令
    Linux下VI操作命令
  • 原文地址:https://www.cnblogs.com/yao/p/442886.html
Copyright © 2011-2022 走看看