/// <summary>
/// 字符串截取
/// </summary>
/// <param name="strValue">要截取的字符串</param>
/// <param name="intLength">截取长度</param>
/// <returns>截取之后的字符串</returns>
public static string truncate(string strValue, int intLength)
{
if (strValue == null)
{
return string.Empty;
}
Regex re = new Regex("<(/)?([^ ]+?)(?: (/)| .*?)?>");
strValue = strValue.Replace(" ", "");
Match m = re.Match(strValue);
if (m.Success)//纯英数
{
strValue = strValue.Replace(m.Value, "");
m = re.Match(strValue);
}
re = new Regex(@"^[A-Za-z0-9]+$");
m = re.Match(strValue);
if (m.Success)
{
if (strValue.Length > intLength)
{
return strValue.Substring(0, intLength) + "...";
}
return strValue;
int n = 0; // 表示当前的字节数
int i = 0; // 要截取的字节数
for (; i < bytes.GetLength(0) && n < intLength; i++)
{
// 偶数位置,如0、2、4等,为UCS2编码中两个字节的第一个字节
if (i % 2 == 0)
{
n++; // 在UCS2第一个字节时n加1
}
else
{
// 当UCS2编码的第二个字节大于0时,该UCS2字符为汉字,一个汉字算两个字节
if (bytes[i] > 0)
{
n++;
}
}
}
// 如果i为奇数时,处理成偶数
if (i % 2 == 1)
{
// 该UCS2字符是汉字时,去掉这个截一半的汉字
if (bytes[i] > 0)
i = i - 1;
// 该UCS2字符是字母或数字,则保留该字符
else
i = i + 1;
}
if (bytes.Length > intLength)
{
strValue = System.Text.Encoding.Unicode.GetString(bytes, 0, i) + "...";
}
else
{
strValue = System.Text.Encoding.Unicode.GetString(bytes, 0, i);
}
return strValue;
}
/// 字符串截取
/// </summary>
/// <param name="strValue">要截取的字符串</param>
/// <param name="intLength">截取长度</param>
/// <returns>截取之后的字符串</returns>
public static string truncate(string strValue, int intLength)
{
if (strValue == null)
{
return string.Empty;
}
Regex re = new Regex("<(/)?([^ ]+?)(?: (/)| .*?)?>");
strValue = strValue.Replace(" ", "");
Match m = re.Match(strValue);
if (m.Success)//纯英数
{
strValue = strValue.Replace(m.Value, "");
m = re.Match(strValue);
}
re = new Regex(@"^[A-Za-z0-9]+$");
m = re.Match(strValue);
if (m.Success)
{
if (strValue.Length > intLength)
{
return strValue.Substring(0, intLength) + "...";
}
return strValue;
}
//混合
byte[] bytes = System.Text.Encoding.Unicode.GetBytes(strValue);int n = 0; // 表示当前的字节数
int i = 0; // 要截取的字节数
for (; i < bytes.GetLength(0) && n < intLength; i++)
{
// 偶数位置,如0、2、4等,为UCS2编码中两个字节的第一个字节
if (i % 2 == 0)
{
n++; // 在UCS2第一个字节时n加1
}
else
{
// 当UCS2编码的第二个字节大于0时,该UCS2字符为汉字,一个汉字算两个字节
if (bytes[i] > 0)
{
n++;
}
}
}
// 如果i为奇数时,处理成偶数
if (i % 2 == 1)
{
// 该UCS2字符是汉字时,去掉这个截一半的汉字
if (bytes[i] > 0)
i = i - 1;
// 该UCS2字符是字母或数字,则保留该字符
else
i = i + 1;
}
if (bytes.Length > intLength)
{
strValue = System.Text.Encoding.Unicode.GetString(bytes, 0, i) + "...";
}
else
{
strValue = System.Text.Encoding.Unicode.GetString(bytes, 0, i);
}
return strValue;
}