用C#截取指定長度的中英文混合字串 改進版

來源:互聯網
上載者:User
很早以前寫過一篇文章(用C#截取指定長度的中英文混合字串),但是對效能沒有測試,有人說我寫的這個方法效能有問題,後來想,可能真會有BT之需求要求傳入一個幾萬K甚至幾M體積的字串進來,那將會影響正則Match的速度,比如文章系統中就極有可能用到,今天有點時間,就改進了一下,代碼如下:

    public static string getStr(string s,int l,string endStr)
    {
        string temp = s.Substring(0, (s.Length < l)?s.Length:l);
        
        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-endStr.Length)
            {
                return temp + endStr;
            }    
        }
        return endStr;
    }



此修改版的方法多加了個參數"string endStr",是指當字串"string s"超過指定長度"int l"時,對結尾的處理,比如要不要加上省略符號"..."或加上其它字元。
另外,添加了省略符號之後,省略符號長度也是算在結果的長度之內了。

    用法如:

    getStr("中國1中國中國中1111中國", 23,"") 
    //output:中國1中國中國中1111中國

    getStr("中國1中國中國中1111中國", 23,"...") 
    //output:中國1中國中國中1111...

    getStr("中國1中國中國中1111中國中國", 23,"")    
    //output:中國1中國中國中1111中國

    getStr("中國1中國中國中1111中國中國", 23,"...")
    //output:中國1中國中國中1111...

----------------------------------------------------------------------

    補充:"kpz"回複說上邊的方法會截取失真,而我又無法做到窮盡測試,所以換了另一種寫法,為了考慮效能結果把邏輯搞的有點"暈",反覆測試了多次,代碼如下:

public static string getStr2(string s, int l,string endStr) 
    { 
        string temp = s.Substring(0, (s.Length < l+1)?s.Length:l+1);    
        byte[] encodedBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(temp);
        
        string outputStr = ""; 
        int count = 0;     
        
        for (int i = 0; i < temp.Length; i++) 
        { 
            if ((int)encodedBytes[i] == 63)
                count += 2; 
            else
                count += 1; 

            if (count <= l-endStr.Length)
                outputStr += temp.Substring(i,1); 
            else if (count>l)    
                break;            
        } 
        
        if (count<=l)
        {
            outputStr=temp;
            endStr="";
        }
        
        outputStr += endStr;    
        
        return outputStr; 
    }

用法和參數含義均同前,注意省略符號也佔位置,算了長度。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.