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

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

问题描述

正如它在标题行中所说的那样,我想在C#中将全角字符转换为hankaku字符和副字符,但不知道如何去做。所以,说ラーメン到ラーメン,反过来说。
这是可以写在一个方法,根据输入的格式自动确定转换需要去的方法?

解决方案

您可以使用字符串.StrConv()方法通过包含对Microsoft.VisualBasic.dll的引用,或者您可以调用

  private const uint LOCALE_SYSTEM_DEFAULT = 0x0800; 
private const uint LCMAP_HALFWIDTH = 0x00400000;
$ b 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语言环境,uint dwMapFlags,字符串lpSrcStr,int cchSrc ,StringBuilder lpDestStr,int cchDest);

您也可以做相反的处理:

  private const uint LCMAP_FULLWIDTH = 0x00800000; 
$ b $ 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 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?

解决方案

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);

and you can also do the reverse:

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天全站免登陆