Пример #1
0
    /// <summary>
    /// 截断字符串,如果str 的长度超过 need,则提取 str 的前 need 个字符,并在尾部加 “...”
    /// </summary>
    public static string Left(string s, int need, bool encode)
    {
        if (s == null || s == "")
        {
            return(string.Empty);
        }

        int len = s.Length;

        // int len = NumChar(s);
        if (len < need / 2)
        {
            return(encode ? TextEncode(s) : s);
        }

        int i, j, bytes = 0;

        for (i = 0; i < len; i++)
        {
            bytes += RegExp.IsUnicode(s[i].ToString()) ? 2 : 1;
            if (bytes >= need)
            {
                break;
            }
        }

        string result = s.Substring(0, i);

        if (len > i)
        {
            for (j = 0; j < 5; j++)
            {
                bytes -= RegExp.IsUnicode(s[i - j].ToString()) ? 2 : 1;
                if (bytes <= need)
                {
                    break;
                }
            }
            result = s.Substring(0, i - j) + "...";
        }
        return(encode ? TextEncode(result) : result);
    }