从给定字符串结尾获取指定字节长度的字符串

 

  

      编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我ABC”,4,应该截为“ABC”,而不是半个我+ABC;输入“我汉DEF”,5,应该输出为“汉DEF”。
      下面代码为从末尾取,总觉得有点繁琐,有更好的方法么?
        /// <summary>
        /// 从给定的字符串后面截取指定字节长度的字符串
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="length">字节长度</param>
        /// <returns>返回的字符串</returns>
        public static string GetSubString(string source, int length)
        {
            string returnstring = string.Empty;
            int sourceByteLen = Encoding.Default.GetBytes(source).Length; //给定字符串的字节长度
            if (sourceByteLen >= length)
            {
                int needLen = length; // 截取的字符长度
                for (int i = length / 2; i <= length; i++)//从后面的字符逐渐往前加直到长度够了
                {
                    int len = Encoding.Default.GetBytes(source.ToCharArray(), source.Length - i, i).Length; 
                    if (len == length)
                    {
                        break;
                    }
                    else if (len > length)
                    {
                        needLen = length - 1;
                        break;
                    }
                }
                byte[] name = new byte[needLen];
                byte[] byteName = Encoding.Default.GetBytes(source);
                for (int i = sourceByteLen - needLen, j = 0; i < sourceByteLen; i++, j++)
                {
                    name[j] = byteName[i];
                }
                returnstring = Encoding.Default.GetString(name);
            }
            else
            {
                throw new Exception("length is bigger than source string byte length");
            }
            return returnstring;
        }
原文地址:https://www.cnblogs.com/chunchengwuchu/p/3407373.html