当前位置:K88软件开发文章中心编程语言.NET.NET01 → 文章内容

C#中求中英文字符串所占字节数的方法

减小字体 增大字体 作者:佚名  来源:翔宇亭IT乐园  发布时间:2018-12-31 11:26:58

:2011-05-06 07:49:07

有时,我们需要求字符串所占的字节数,而中文和英文所占的字节数往往是不同的,则在求中英文混合的字符串时,需要一定的技巧。本文就给出了求中英文混合字符串所占字节数的方法。

源代码如下:

using System;

using System.Collections.Generic;

using System.Text; 

namespace jiqiao_Console

{

    class StringOP

    {

        /// <summary>

        /// 获取中英文混排字符串的实际长度(字节数)

        /// </summary>

        /// <param name="str">要获取长度的字符串</param>

        /// <returns>字符串的实际长度值(字节数)</returns>

        public int getStringLength(string str)

        {

            if (str.Equals(string.Empty))

                return 0;

            int strlen = 0;

            ASCIIEncoding strData = new ASCIIEncoding();

            byte[] strBytes = strData.GetBytes(str);

            for (int i = 0; i <= strBytes.Length - 1; i++)

            {

                if (strBytes[i] == 63)

                    strlen++;

                strlen++;

            }

            return strlen;

        }

    }

 

    class TestMain

    {

        static void Main()

        {

            StringOP sop = new StringOP();

            string str = "I Love China!I Love 北京!";

            int iLen = sop.getStringLength(str);

            Console.WriteLine("字符串" + str + "的字节数为:" + iLen.ToString());

            Console.ReadKey();

        }

    }

}

注意:在以上名为jiqiao_Console的命名空间中定义了两个类,一个类用于操作字符串的定义,另外一个类用于检验。

以上程序的输出结果为:


C#中求中英文字符串所占字节数的方法