栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

C#中英文混合字符串截取函数

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#中英文混合字符串截取函数

代码一

/// 
    /// 截断字符串
    /// 
    /// 最大长度
    /// 原字符串
    /// 
    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# 截取字符串方法(包含中英混合)的实现代码,需要的朋友可以参考一下

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/127062.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号