Converting zenkaku characters to hankaku and vice-versa in C#(在 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,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# 中将 zenkaku 字符转换为 hankaku,反之亦然
基础教程推荐
- Moq It.Is<>不匹配 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
