zoukankan      html  css  js  c++  java
  • C# 按不同的字节编码,通过字节数去截取字符串

            /// <summary>
            /// 按不同的字节编码,通过字节数去截取字符串
            /// 数据库UTF-8 1个数字、字母、英文符号算1个长度 1个中文、中文符号算3个长度
            /// </summary>
            /// <param name="origStr">需截取的字符串</param>
            /// <param name="bytesLength">需截取的字节长度</param>
            /// <param name="dstEncoding">截取的字节编码类型</param>
            /// <returns></returns>
            public static string GetSubString(string origStr, int bytesLength, Encoding dstEncoding)
            {
                if (origStr == null || origStr.Length == 0 || bytesLength < 0)
                    return "";
                int bytesCount = dstEncoding.GetByteCount(origStr);
                if (bytesCount > bytesLength)
                {
                    int readyLength = 0;
                    int byteLength;
                    for (int i = 0; i < origStr.Length; i++)
                    {
                        byteLength = dstEncoding.GetByteCount(new char[] { origStr[i] });
                        readyLength += byteLength;
                        if (readyLength == bytesLength)
                        {
                            origStr = origStr.Substring(0, i + 1);// + "..."; 加省略号
                            break;
                        }
                        else if (readyLength > bytesLength)
                        {
                            origStr = origStr.Substring(0, i);// + "..."; 加省略号
                            break;
                        }
                    }
                }
                return origStr;
            }
    sting newStr = GetSubString(origStr, bytesLength, Encoding.UTF8);
  • 相关阅读:
    POJ 1113 Wall
    POJ 2159 Ancient Cipher
    POJ 3253 Fence Repair
    HDU 5444 Elven Postman
    HDU 5432 Pyramid Split
    数据库 组合查询
    数据库 简单的数据查询
    数据库 聚合函数与分组
    数据库 使用DML语句更改数据
    数据库的数据完整性
  • 原文地址:https://www.cnblogs.com/gilbert/p/9482326.html
Copyright © 2011-2022 走看看