程序员的部落

导航

截取一定长度的字符串

    #region 截取一定长度的字符串
    /// <summary>
    /// 从字符串左边开始截取一定长度的字符串
    /// </summary>
    /// <param name="stringToSub">要截取的字符串</param>
    /// <param name="length">要截取的长度(以字符为单位,1中文为2字符)</param>
    /// <returns>返回截取到的数据</returns>
    public static string GetFirstString(string stringToSub, int length)
    {
        if (stringToSub.Length < length)
        {
            return stringToSub;
        }
        Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
        char[] stringChar = stringToSub.ToCharArray();
        StringBuilder sb = new StringBuilder();
        int nLength = 0;
        bool isCut = false;
        for (int i = 0; i < stringChar.Length; i++)
        {
            if (regex.IsMatch((stringChar[i]).ToString()))
            {
                sb.Append(stringChar[i]);
                nLength += 2;
            }
            else
            {
                sb.Append(stringChar[i]);
                nLength = nLength + 1;
            }

            if (nLength > length)
            {
                isCut = true;
                break;
            }
        }
        if (isCut)
            return sb.ToString() + "..";
        else
            return sb.ToString();
    }
    #endregion

posted on 2009-04-02 10:12  程序员的部落  阅读(303)  评论(0编辑  收藏  举报