C#中英文混合字符串截取函数
作者:shangke 时间:2023-01-19 06:02:55
代码一
/// <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#,中英文,字符串截取
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
springcloud中Ribbon和RestTemplate实现服务调用与负载均衡
2022-06-30 14:58:45
![](https://img.aspxhome.com/file/2023/5/61585_0s.png)
mybatis-plus自动填充插入更新时间有8小时时差
2021-07-26 07:18:40
![](https://img.aspxhome.com/file/2023/7/74767_0s.png)
C#语言中条件与&&与条件或||的区别
2022-10-06 22:51:55
Android中FoldingLayout折叠布局的用法及实战全攻略
2021-05-23 19:29:17
![](https://img.aspxhome.com/file/2023/9/137149_0s.jpg)
Java读取properties配置文件的8种方式汇总
2022-05-03 17:11:34
![](https://img.aspxhome.com/file/2023/9/96079_0s.png)
mybatisplus中EntityWrapper的常用方法
2022-11-09 21:52:00
C#连接ODBC数据源的方法
2023-04-20 07:30:33
C++内存对齐的实现
2023-11-22 00:42:20
基于Hibernate中配置文件的学习(分享)
2022-02-11 12:03:31
![](https://img.aspxhome.com/file/2023/8/80858_0s.png)
Java中对象的比较操作实例分析
2023-03-05 03:58:09
![](https://img.aspxhome.com/file/2023/7/85397_0s.png)
Android App开发中自定义View和ViewGroup的实例教程
2021-06-11 08:58:03
![](https://img.aspxhome.com/file/2023/5/138555_0s.png)
Android RIL使用详解
2021-09-30 18:06:45
![](https://img.aspxhome.com/file/2023/2/137182_0s.png)
Android开发中Intent.Action各种常见的作用汇总
2022-10-08 10:24:53
SpringBoot接口调用之后报404问题的解决方案
2021-08-31 15:25:03
![](https://img.aspxhome.com/file/2023/4/86834_0s.png)
Java 中 hashCode() 与 equals() 的关系(面试)
2023-08-29 18:03:57
C#截图程序类似腾讯QQ截图实现代码
2023-05-07 04:01:01
![](https://img.aspxhome.com/file/2023/1/100191_0s.jpg)
Spring Boot集成MyBatis的方法
2021-11-03 23:11:05
![](https://img.aspxhome.com/file/2023/6/64486_0s.png)
详解C#使用AD(Active Directory)验证内网用户名密码
2023-03-03 23:17:47
mybatis中的if test判断入参的值问题
2023-11-16 08:13:44
![](https://img.aspxhome.com/file/2023/9/59579_0s.png)
C++类中的特殊成员函数示例详解
2023-11-07 13:02:08