c#字符串中英文混合,根据字符长度截取的函数

今天一个朋友需要一段代码,能够处理中英混合字符串按照字符长度截取功能。

我想了一下,这个功能应该是UI端为了上下显示比例看起来比较协调而需要。

好了,直接上代码吧。。。。。。

string calculate = subStringForBytes(“abc你d好efgh”, 6);
 1 protected string subStringForBytes(string strValue,int bytLen)
 2         {
 3             string tempString = string.Empty;
 4             if (GetLength(strValue) <= bytLen)
 5             {
 6                 return strValue;
 7             }
 8             else
 9             {
10                 int cutIndex = bytLen / 2;
11                 tempString = strValue.Substring(0, cutIndex);
12                 while (GetLength(tempString) < bytLen)//如果想要效果“abcd你好efgh = abcd”,修改成 “GetLength(tempString) <= bytLen”
13                 {
14                     if (GetLength(tempString + strValue.Substring(cutIndex, 1)) > bytLen)
15                     {
16                         break;
17                     }
18                     else
19                     {
20                         tempString = tempString + strValue.Substring(cutIndex, 1);
21                         cutIndex = cutIndex + 1;
22                     }
23                 }
24                 return tempString;
25             }
26         }
1 protected int GetLength(string strValue)
2         {
3             byte[] myByte = System.Text.Encoding.Default.GetBytes(strValue);
4             return myByte.Length;
5         }
原文地址:https://www.cnblogs.com/dfdfding/p/5534877.html