按字节截取字符串
因为中文和英文所占位置不同,一个能显示5个中文的位置应该能显示10个英文
//截取字符串
public static string GetSubString(string mText, int startIndex, int byteCount)
{
if (byteCount < 1) return string.Empty;
if (System.Text.Encoding.Default.GetByteCount(mText) <= byteCount)
{
return mText;
}
else
{
if (startIndex == 0)
{
byte[] txtBytes = System.Text.Encoding.Default.GetBytes(mText);
byte[] newBytes = new byte[byteCount];
for (int i = 0; i < byteCount; i++)
newBytes[i] = txtBytes[i];
return System.Text.Encoding.Default.GetString(newBytes);
}
else
{
string tmp = GetSubString(mText, 0, startIndex - 1);
mText = mText.Substring(tmp.Length);
return GetSubString(mText, 0, byteCount);
}
}
}
public static string GetSubString(string mText, int startIndex)
{
return GetSubString(mText, startIndex, System.Text.Encoding.Default.GetByteCount(mText) - startIndex + 1);
}
/// <summary>
/// 得到字符串的长度,一个汉字算2个字节
/// </summary>
/// <param name="str">字符串</param>
/// <returns>返回字符串长度</returns>
public static int GetLength(string str)
{
if (str.Length == 0) return 0;
ASCIIEncoding ascii = new ASCIIEncoding();
int tempLen = 0;
byte[] s = ascii.GetBytes(str);
for (int i = 0; i < s.Length; i++)
{
if ((int)s[i] == 63)
{
tempLen += 2;
}
else
{
tempLen += 1;
}
}
return tempLen;
}