C# 중국어 및 영어 인터셉트 고정 문자 길이

C# 중국어 및 영어 인터셉트 고정 문자 길이

C#에서 영문과 한자의 굵기가 다르며 길이를 가로채면 한자가 변환됨

 /// <summary>
    /// 中英文截取固定字符长
    /// </summary>
    /// <param name="oriStr">原始字符</param>
    /// <param name="length">需要长度(英文1个,中文2个)</param>
    /// <returns></returns>
    public static string GetSubString(string oriStr,int length)
    {
    
    
        string resultStr = string.Empty;

        if (string.IsNullOrEmpty(oriStr)) {
    
     return resultStr; }

        var encoding = new System.Text.ASCIIEncoding();
        int _length = 0;
        int realStrLength = 0;

        byte[] bytes = encoding.GetBytes(oriStr);
        for (int i = 0; i < bytes.Length; i++)
        {
    
    
            // 汉字
            if ((int)bytes[i] == 63)
                _length += 2;
            // 英文
            else
                _length += 1;

            if(_length > length)
            {
    
    
                break;
            }
            else
            {
    
    
                realStrLength++;
            }
        }
        resultStr = oriStr.Substring(0, realStrLength);
        return resultStr;
    }

Supongo que te gusta

Origin blog.csdn.net/waterdsm/article/details/114285448
Recomendado
Clasificación