//截取字符串
public static string LeftStr(string str, int len)
{
if (str.Length == 0) return str;
ASCIIEncoding ascii = new ASCIIEncoding();
int tempLen = 0;
string tempString = "";
byte[] s = ascii.GetBytes(str);
for (int i = 0; i < s.Length; i++)
{
if ((int)s[i] == 63)
{
tempLen += 2;
}
else
{
tempLen += 1;
}
try
{
tempString += str.Substring(i, 1);
}
catch
{
break;
}
if (tempLen > len)
break;
}
return tempString;
}
代码2
//截取字符串
public static string Cut_Str(String iStr,int len,String ended) {
if (String.IsNullOrEmpty(iStr)) return String.Empty;
byte[] bytes = Encoding.Unicode.GetBytes(iStr);
int j = 0;
int i = 0;
for (; i < bytes.Length && j < len; i++) {
if (i % 2 == 0)
j++;
else if (bytes[i] > 0) //汉字
j++;
}
if (i % 2 == 1) {
if (bytes[i] > 0)
i--;
else
i++;
}
if (j <= (len - 1)) ended = String.Empty;
return Encoding.Unicode.GetString(bytes, 0, i) + ended;
}
本文介绍了两种在C#中实现的字符串截取方法。第一种方法使用ASCII编码来处理包含特殊字符的字符串,确保不会截断半个字符。第二种方法采用Unicode编码,能够更准确地处理包含中文等双字节字符的字符串,并提供了一个结束符参数用于指定截断后的附加字符。
223

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



