C#计算含中文字符串的长度

近日在工作中正好遇见了判断是否为中文字符的问题,把代码写上来,方便记忆

 

using System;
using System.Text.RegularExpressions;

namespace StrTest
{
    class Program
    {
        static void Main(string[] args)
        {
            int strLength = 0;

            //半角
            string testStr = "这是TEST";
            strLength = GetStrLength(testStr);
            Console.WriteLine("str:{0},len:{1}", testStr, strLength);

            //全角
            testStr = "TEST全角";
            strLength = GetStrLength(testStr);
            Console.WriteLine("str:{0},len:{1}", testStr, strLength);

            Console.Read();
        }

        /// <summary>
        /// 获取实际占用长度
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>真实长度</returns>
        static int GetStrLength(string str)
        {
            int strLength = 0;
            //中文字符正则
            Regex rx = new Regex("^[\u4e00-\u9fa5]$");
            //全角字符正则
            Regex rx1 = new Regex("^[\uFF00-\uFFFF]$");

            for (int i = 0; i < str.Length; i++)
            {
                if (rx.IsMatch(str[i].ToString()) || rx1.IsMatch(str[i].ToString()))
                {//如果为中文字符或全角字符,字符串长度加2
                    strLength += 2;
                }
                else
                {//否则加1
                    strLength += 1;
                }
            }

            return strLength;
        }
    }
}

以下这是结果:

这段代码只适用于中文字符和英文字符以及半角字符同时存在的情况,其他文字的情况并未进行测试

转载于:https://www.cnblogs.com/PandaPYH/p/3669921.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值