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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值