很早以前寫過一篇文章(用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;
}
用法和參數含義均同前,注意省略符號也佔位置,算了長度。