C#中的String.Length獲取中文字符串長度出錯


項目需要截取中文字符,中文字符大於255的時候,需要截取字符,在這里出現了問題。因為使用的是String.length。

Length 屬性返回此實例中 Char 對象的個數,而不是 Unicode 字符個數。 原因在於一個 Unicode 字符可能會用多個 Char 表示。 使用System.Globalization.StringInfo 類來處理每個 Unicode 字符而不是每個 Char

附上獲取中文字符長度,並截取的類的代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common
{
   public static class SplitWorld
    {
        /// <summary>
        /// 獲取中英文混排字符串的實際長度(字節數)
        /// </summary>
        /// <param name="str">要獲取長度的字符串</param>
        /// <returns>字符串的實際長度值(字節數)</returns>
        public static int Length(string str)
        {
            if (str.Equals(string.Empty))
                return 0;
            int strlen = 0;
            ASCIIEncoding strData = new ASCIIEncoding();
            //將字符串轉換為ASCII編碼的字節數字
            byte[] strBytes = strData.GetBytes(str);
            for (int i = 0; i <= strBytes.Length - 1; i++)
            {
                if (strBytes[i] == 63)  //中文都將編碼為ASCII編碼63,即"?"號
                    strlen++;
                strlen++;
            }
            return strlen;
        }

        /// <summary>截取指定字節長度的字符串</summary> 
        /// <param name="str">原字符串</param>
        ///<param name="len">截取字節長度</param> 
        /// <returns>string</returns>
        public static string SubString(string str, int len)
        {
            string result = string.Empty;// 最終返回的結果
            if (string.IsNullOrEmpty(str))
            {
                return result;
            }
            int byteLen = System.Text.Encoding.Default.GetByteCount(str);
            // 單字節字符長度
            int charLen = str.Length;
            // 把字符平等對待時的字符串長度
            int byteCount = 0;
            // 記錄讀取進度 
            int pos = 0;
            // 記錄截取位置 
            if (byteLen > len)
            {
                for (int i = 0; i < charLen; i++)
                {
                    if (Convert.ToInt32(str.ToCharArray()[i]) > 255)
                    // 按中文字符計算加 2 
                    {
                        byteCount += 2;
                    }
                    else
                    // 按英文字符計算加 1 
                    {
                        byteCount += 1;
                    }
                    if (byteCount > len)
                    // 超出時只記下上一個有效位置
                    {
                        pos = i;
                        break;
                    }
                    else if (byteCount == len)// 記下當前位置
                    {
                        pos = i + 1; break;
                    }
                } if (pos >= 0)
                {
                    result = str.Substring(0, pos);
                }
            }
            else { result = str; } return result;
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM