如何统计日英混合字符串所需的列数?

发布于 2024-11-26 14:31:12 字数 193 浏览 1 评论 0原文

我的字符串包含日语(双宽)和英语(单宽)字符的混合:

string str = "女性love";

在 C# 中,我的方法必须将日语字符计为两列,将英语字符计为一列。 这样上面的字符串应该有 8 列:

2 + 2 + 1 + 1 + 1 + 1 = 8

My string contains a mix of japanese (double width) and english (single width) characters:

string str = "女性love";

In C#, my method has to count japanese characters as two columns and english characters as one.
So that the above string should get me a 8 columns :

2 + 2 + 1 + 1 + 1 + 1 = 8

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

请叫√我孤独 2024-12-03 14:31:12

也许你想要这样的东西,非常粗糙,但是通过一点点工作,你可以让它变得更好:

    string str = "女性love";
    int iTotal = 0;

    str.ToList().ForEach(ch=>{
        int iCode = ch;
        if(iCode>= 65 && iCode <= 122)
            iTotal++;
        else 
            iTotal +=2;
    });

//65 is 'a', 122 is 'z'.  iTotal = 8 //in this case

现在为什么 System.Text.Encoding.UTF8.GetBytes(str).Length 返回 10,它只是导致 UTF8 编码规范。请点击此链接Joel on Unicode 并阅读整篇文章。特别是关于这个问题最重要的事情:

在 UTF-8 中,从 0 到 127 的每个代码点都存储在单个字节中。
仅使用 2、3 存储代码点 128 及以上,实际上最多可存储 6 个代码点
字节

检查你的日文字母代码点,你会找出为什么它返回 10 的答案。

编辑

请注意,此代码实际上将英文字母与“其他”分开,而不仅仅仅与日本的。如果您只需要过滤日语字母,因为您可能需要处理阿拉伯语、埃布拉语、俄语或其他语言,您需要了解日语字母在代码方面的限制

问候。

Probbaly you want something like this, very rough one, but by working a little bit on it you can make it much nicer:

    string str = "女性love";
    int iTotal = 0;

    str.ToList().ForEach(ch=>{
        int iCode = ch;
        if(iCode>= 65 && iCode <= 122)
            iTotal++;
        else 
            iTotal +=2;
    });

//65 is 'a', 122 is 'z'.  iTotal = 8 //in this case

Now what about why System.Text.Encoding.UTF8.GetBytes(str).Length returns 10, it simply cause UTF8 ecoding specification. Follow this link Joel on Unicode and read entire article. In particular here is most importnat stuff in regard of this question:

In UTF-8, every code point from 0-127 is stored in a single byte.
Only code points 128 and above are stored using 2, 3, in fact, up to 6
bytes

Check your Japanese letters code points and you will figure out an aswer on why it returns 10.

EDIT

Pay attention that this code, actually separate English letters from "others", and not only from Japanese ones. If you need to filter only on Japanese ones, cause may be you need to deal with Arabic, Ebraic, Russian or whatever, you need to know limits, in terms of codes, of Japanese alphabet.

Regards.

自演自醉 2024-12-03 14:31:12

尝试这样的事情:

int bCnt = System.Text.Encoding.UTF8.GetBytes(str).Length; //Select the appropriate encoding, if not UTF8

Try something like this:

int bCnt = System.Text.Encoding.UTF8.GetBytes(str).Length; //Select the appropriate encoding, if not UTF8
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文