zoukankan      html  css  js  c++  java
  • 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         }
  • 相关阅读:
    我所理解的执行力
    iOS移动开发周报-第20期
    iOS移动开发周报-第19期
    iOS开发如何提高
    iOS移动开发周报-第18期
    iOS移动开发周报-第17期
    一起入门python3之元组和数列
    提权笔记本
    sqlmap笔记本
    SQL注入自学[第一学:一个简单的注入环境的编写]
  • 原文地址:https://www.cnblogs.com/dfdfding/p/5534877.html
Copyright © 2011-2022 走看看