C# 截取指定长度字符串方法

    /// <summary>
    /// 截取指定长度字符串
    /// </summary>
    /// <param name="inputString">要处理的字符串</param>
    /// <param name="len">指定长度</param>
    /// <returns>返回处理后的字符串</returns>
    public string ClipString(string inputString, int len)
    {

        bool isShowFix = false;
        if (len % 2 == 1)
        {
            isShowFix = true;
            len--;
        }
        System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
        int tempLen = 0;
        string tempString = "";
        byte[] s = ascii.GetBytes(inputString);
        for (int i = 0; i < s.Length; i++)
        {
            if ((int)s[i] == 63)
                tempLen += 2;
            else
                tempLen += 1;

            try
            {
                tempString += inputString.Substring(i, 1);
            }
            catch
            {
                break;
            }

            if (tempLen > len)
                break;
        }

        byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
        if (isShowFix && mybyte.Length > len)
            tempString += "…";
        return tempString;
    }

 

posted @ 2015-06-26 15:01  bubadao  阅读(4209)  评论(1编辑  收藏  举报