这个函数也没有什么特别之处,就是可以截取一定长度的字符串,可能小特点就是len是字节,解决了汉字与英文字节不一样导致直接截取到的长度不一样的问题,
#region 字符串截取函数
public static string CutString(string inputString,int len)
{
ASCIIEncoding ascii = new ASCIIEncoding();
int tempLen=0;
string tempString="";
byte[] s = ascii.GetBytes(inputString);
for(int i=0;i<s.Length;i++)
{
if((int)s[i]==63)
{
tempLen+=2;
}
else
{
tempLen+=1;
}
try
{
tempString+=inputString.Substring(i,1);
}
catch
{
break;
}
if(tempLen>len)
break;
}
//如果截过则加上半个省略号
byte[] mybyte=System.Text.Encoding.Default.GetBytes(inputString);
if(mybyte.Length>len)
tempString+="…";
return tempString;
}
#endregion
博客展示了一个C#的字符串截取函数CutString。该函数接收输入字符串和截取长度,通过ASCII编码判断字符长度,循环处理字符串,若截取后长度超过指定值则添加省略号,最终返回截取后的字符串。
605

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



