C#中英文混合字符串截取函數(shù)
更新時間:2013年09月10日 16:31:02 投稿:shangke
這篇文章介紹了C#中英文混合字符串截取函數(shù),有需要的朋友可以參考一下
代碼一
/// <summary>
/// 截斷字符串
/// </summary>
/// <param name="maxLength">最大長度</param>
/// <param name="str">原字符串</param>
/// <returns></returns>
public static string CutStr(int maxLength, string str)
{
string temp = str;
if (Regex.Replace(temp, "[\u4e00-\u9fa5]", "zz", RegexOptions.IgnoreCase).Length <= maxLength)
{
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 <= maxLength - 3)
{
return temp + "...";
}
}
return "...";
}
代碼二
private string GetByteString(string center, int maxlen, string endStr)
{
string temp = center.Substring(0, (center.Length < maxlen + 1) ? center.Length : maxlen + 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 <= maxlen - endStr.Length)
outputStr += temp.Substring(i, 1);
else if (count > maxlen)
break;
}
if (count <= maxlen)
{
outputStr = temp;
endStr = "";
}
outputStr += endStr;
return outputStr;
}
以上就是C# 截取字符串方法(包含中英混合)的實現(xiàn)代碼,需要的朋友可以參考一下
相關(guān)文章
非常實用的C#字符串操作處理類StringHelper.cs
這篇文章主要為大家詳細(xì)介紹了非常實用的C#字符串操作處理類StringHelper.cs,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07
C#實現(xiàn)讀取被進(jìn)程占用的文件實現(xiàn)方法
這篇文章主要介紹了C#實現(xiàn)讀取被進(jìn)程占用的文件實現(xiàn)方法,涉及C#進(jìn)程操作及文件讀取的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-08-08
C#中的Hangfire和Quartz.NET 任務(wù)調(diào)度的區(qū)別解析
Hangfire 和 Quartz.NET 是兩種常見的 C# 任務(wù)調(diào)度庫,它們有不同的特點和使用場景,本文給大家介紹C#中的Hangfire和Quartz.NET 任務(wù)調(diào)度的區(qū)別,感興趣的朋友一起看看吧2024-08-08
C#中靜態(tài)構(gòu)造函數(shù)的幾點說明介紹
本篇文章主要是對C#中靜態(tài)構(gòu)造函數(shù)的幾點說明進(jìn)行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01

