开发通用类 - 字符串截断篇

/// <summary>
/// 截断字符串
/// </summary>
/// <param name="source">源字符串</param>
/// <param name="length">截取长度</param>
/// <param name="isAddEllipsis">结尾是否带有省略号(省略号占用2个长度)</param>
/// <returns></returns>
public static string CutStringForString(string source, int length, bool isAddEllipsis)
{
    // 空字符串
    if (string.IsNullOrEmpty(source))
    {
        return string.Empty;
    }

    // 长度不够
    char[] sourceArray = source.ToCharArray();
    if (sourceArray.Length <= length)
    {
        return source;
    }

    // 超长、截断
    string newStr = source.Substring(0, (isAddEllipsis ? length - 2 : length));
    if (isAddEllipsis)
    {
        newStr += "……";
    }

    return newStr;

}

/// <summary>
/// 根据字节长度截取字符串
/// </summary>
/// <param name="source">源字符串</param>
/// <param name="length">截取长度</param>
/// <param name="isAddEllipsis">结尾是否带有省略号(省略号占用4个字节)</param>
/// <returns></returns>
public static string CutStringForByte(string source, int length, bool isAddEllipsis)
{
    // 空字符串
    if (string.IsNullOrEmpty(source))
    {
        return string.Empty;
    }

    // 长度不够
    int sourceByteLength = 0;
    char[] sourceArray = source.ToCharArray();
    for (int i = 0; i < sourceArray.Length; i++)
    {
        if (Convert.ToInt32(sourceArray[i]) > 255)
        {
            sourceByteLength += 2;
        }
        else
        {
            sourceByteLength++;
        }
    }
    if (sourceByteLength <= length)
    {
        return source;
    }

    // 长度超长
    //如果结尾添加 … 则要在原本截取长度基础上减去2
    if (isAddEllipsis)
    {
        length = length - 4;
    }
    int k = 0;
    var newStr = new StringBuilder();
    sourceByteLength = 0;
    while (sourceByteLength < length)
    {
        newStr.Append(sourceArray[k]);
        if (Convert.ToInt32(sourceArray[k]) > 255)
        {
            sourceByteLength += 2;
        }
        else
        {
            sourceByteLength++;
        }
        k++;
    }
    if (isAddEllipsis)
    {
        newStr.Append("……");
    }

    return newStr.ToString();
}

 

posted @ 2012-08-10 10:07  liyuzhao  阅读(598)  评论(1编辑  收藏  举报