使用如下函数便好,其实inputString是源串,len是要截取的长度(以半角计算)。
原理很简单,就是逐个遍历源串中的字符,如果该字符是全角,则认为它占两个长度,如果是半角,就认为它占一个长度。
public static string CutString(string inputString, int len)
{
string tempString = string.Empty;
for (int i = 0, tempIndex = 0; i < inputString.Length; ++i, ++tempIndex)
{
if (System.Text.Encoding.UTF8.GetBytes(new char[] { inputString[i] }).Length > 1)
{
++tempIndex;
}
if (tempIndex >= len)
{
tempString += "...";
break;
}
tempString += inputString[i];
}
return tempString;
}
本文介绍了一个用于处理字符串截取并考虑全角与半角字符的函数。详细解释了如何通过逐个遍历源串,判断字符长度(全角为2,半角为1),实现按指定长度截取字符串的功能,并在超过指定长度时添加省略号。此技术适用于文本处理和数据展示等场景。
1万+

被折叠的 条评论
为什么被折叠?



