zoukankan      html  css  js  c++  java
  • 从给定字符串结尾获取指定字节长度的字符串

     

      

          编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我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;
            }
  • 相关阅读:
    git 命令图解
    tensorflow 保存及其加载
    tensorflow estimator 与 model_fn 是这样沟通的
    面向过程、面向函数、面向对象的区别浅谈
    Python 中自定义spark转换器
    pyspark 好用多了,放弃scala
    variable_scope 与 name_scope 区别
    tensorflow 条件语句与循环语句
    html 标签内部元素上下居中
    html 标签内部元素左右居中
  • 原文地址:https://www.cnblogs.com/chunchengwuchu/p/3407373.html
Copyright © 2011-2022 走看看