使用拓展方法,方便调用
截取字符串(中英文)
/// <summary>
/// 截取字符串(中英文)
/// </summary>
/// <returns></returns>
public static string Cut(this string str, int length, string replacetxt = "...")
{
int strLength = 0;
StringBuilder strb = new StringBuilder();
char[] Temp = str.ToCharArray();
for (int i = 0; i != Temp.Length; i++)
{
if (strLength >= length)
{
strb.Append(replacetxt);
break;
}
else
{
if (((int)Temp[i]) < 255)
{
strLength++;
}
else
{
strLength = strLength + 2;
}
strb.Append(Temp[i]);
}
}
return strb.ToString();
}
获取拆分后的字符串列表
/// <summary>
/// 获取拆分后的字符串列表。
/// </summary>
public static ArrayList SeparateSubString(this string str, int subStringCharNumber)
{
ArrayList resultList = new ArrayList();
string tempStr = str;
int charNumber = subStringCharNumber;
int totalCount = 0;
string mSubStr = "";
for (int i = 0; i < tempStr.Length; i++)
{
string mChar = tempStr.Substring(i, 1);
int byteCount = Encoding.Default.GetByteCount(mChar);//关键点判断字符所占的字节数
if (byteCount == 1)
{
totalCount++;
mSubStr += mChar;
if (totalCount == charNumber || i == tempStr.Length - 1)
{
resultList.Add(mSubStr);
totalCount = 0;
mSubStr = "";
}
}
else if (byteCount > 1)
{
totalCount += 2;
if (totalCount > charNumber)
{
resultList.Add(mSubStr);
if (i == tempStr.Length - 1)
{
mSubStr = mChar;
resultList.Add(mSubStr);
}
else
{
totalCount = 2;
mSubStr = mChar;
}
}
else if (totalCount == charNumber)
{
mSubStr += mChar;
resultList.Add(mSubStr);
totalCount = 0;
mSubStr = "";
}
else if (i == tempStr.Length - 1)
{
mSubStr += mChar;
resultList.Add(mSubStr);
}
else
{
mSubStr += mChar;
}
}
}
return resultList;
}