您的位置:程序门 -> .net技术 -> c#



一个关于编码的问题


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


一个关于编码的问题[已结贴,结贴人:jjyjjyjjy]
发表于:2007-03-23 10:43:50 楼主
using   system;
public   class   code
{
        public   static   void   main()
        {
                string   strtemp   =   "abcdefg   某某某 ";
                int   i   =   system.text.encoding.default.getbytes(strtemp).length;
                int   j   =   strtemp.length;
                system.console.writeline(system.text.encoding.default.bodyname);
                system.console.writeline(i);
                system.console.writeline(j);
        }
}
我这里的运行结果:
gb2312
11   //对这个结果不解,知道的解释一下,汉字不是2个字节编码?
11
发表于:2007-03-23 10:49:341楼 得分:5
//我的测试结果是
gb2312
14
11

系统默认是gb2312
而c#默认是utf8编码
这里的string.length()不是代表byte
是代表char有多少个
发表于:2007-03-23 11:30:252楼 得分:0
这个难度与系统有关,我的是2003server,测试编码结果硬是11,而不是14,不解...
发表于:2007-03-23 11:53:363楼 得分:5
你的系统的问题吧

我测试也是14

并且改了改代码     发现允许和预期没有差别

using   system;
public   class   code
{
public   static   void   main()
{
string   strtemp   =   "abcdefg   某某某 ";
byte[]     l=   system.text.encoding.default.getbytes(strtemp);
foreach(byte   b   in   l)
{    
      system.console.writeline(b);
}
int   i=l.length;
int   j   =   strtemp.length;
system.console.writeline(system.text.encoding.default.bodyname);
system.console.writeline(i);
system.console.writeline(j);
}
}

输出
c:\> a
97
98
99
100
101
102
103
32
196
179
196
179
196
179
gb2312
14
11
发表于:2007-03-23 12:20:384楼 得分:5
///   <summary>
                ///   检测含有中文字符串的实际长度
                ///   </summary>
                ///   <param   name= "str "> 字符串 </param>
                private   int   len(string   str)
                {
                        system.text.asciiencoding   n   =   new   system.text.asciiencoding();
                        byte[]   b   =   n.getbytes(str);
                        int   l   =   0;   //   l   为字符串之实际长度
                        for   (int   i=0;i   <=   b.length-1;i++)
                        {
                                if   (b[i]   ==63)   //判断是否为汉字或全脚符号
                                {
                                        l++;
                                }
                                l++;
                        }                         return   l;
                }
发表于:2007-03-23 12:23:205楼 得分:5
system.text.encoding.default.getbytecount(str);//或者
发表于:2007-03-23 12:39:206楼 得分:0
呵呵,回家再测试一下,晚上结贴
发表于:2007-03-23 13:26:547楼 得分:0
帮顶   !


快速检索

最新资讯
热门点击