在 C# 中将 zenkaku 字符转换为 hankaku,反之亦然 [英] Converting zenkaku characters to hankaku and vice-versa in C#

查看:27
本文介绍了在 C# 中将 zenkaku 字符转换为 hankaku,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题行中所说,我想在 C# 中将 zenkaku 字符转换为 hankaku 字符和vic-vrsa,但不知道该怎么做.所以,说ラーメン"到ラーメン",反之亦然.是否有可能以一种根据输入格式自动确定转换需要走哪条路的方法来编写它?

As it says in the header line, I want to convert zenkaku characters to hankaku ones and vice-vrsa in C#, but can't figure out how to do it. So, say "ラーメン" to "ラーメン" and the other way around. Would it be possible to write this in a method which determines automatically which way the conversion needs to go, based on the format of the input?

推荐答案

您可以使用 Strings.StrConv() 方法通过包含对 Microsoft.VisualBasic.dll 的引用,或者您可以 p/invoke LCMapString() 原生函数:

You can use the Strings.StrConv() method by including a reference to Microsoft.VisualBasic.dll, or you can p/invoke the LCMapString() native function:

private const uint LOCALE_SYSTEM_DEFAULT = 0x0800;
private const uint LCMAP_HALFWIDTH = 0x00400000;

public static string ToHalfWidth(string fullWidth)
{
    StringBuilder sb = new StringBuilder(256);
    LCMapString(LOCALE_SYSTEM_DEFAULT, LCMAP_HALFWIDTH, fullWidth, -1, sb, sb.Capacity);
    return sb.ToString();
}

[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern int LCMapString(uint Locale, uint dwMapFlags, string lpSrcStr, int cchSrc, StringBuilder lpDestStr, int cchDest);

你也可以反过来做:

private const uint LCMAP_FULLWIDTH = 0x00800000;

public static string ToFullWidth(string halfWidth)
{
    StringBuilder sb = new StringBuilder(256);
    LCMapString(LOCALE_SYSTEM_DEFAULT, LCMAP_FULLWIDTH, halfWidth, -1, sb, sb.Capacity);
    return sb.ToString();
}

至于检测输入字符串的格式,我不知道不先进行转换并比较结果的简单方法.(如果字符串同时包含全角和半角字符怎么办?)

As for detecting the format of the input string, I'm not aware of an easy way without doing a conversion first and comparing results. (What if the string contains both full-width and half-width characters?)

这篇关于在 C# 中将 zenkaku 字符转换为 hankaku,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆