【问题标题】:Determine whether a character is diacritic?确定一个字符是否是变音符号?
【发布时间】:2014-03-11 19:02:43
【问题描述】:

我正在使用下一个函数来转换一个变音符号,然后获取该字符的 Keycode,但在调用此方法之前,我需要先知道该字符是否为变音符号,以免对该方法进行冗余调用这应该将变音符号与非变音符号字符区分开来。

那么,如何判断一个字符是否有变音符号?

PS:请参阅代码中标记的commens。

这个想法是,对于字符O,该方法应该返回一个79,对于字符Ó,该方法将删除变音符号,所以我得到一个O,然后我再次调用该函数O,返回另一个79,但是如果在键盘布局上找不到该字符,即使该字符不是变音符号,该方法也会尝试删除变音符号,并一直再次调用相同的函数,所以我需要判断字符是否是变音符号。

Public Shared Function GetKeyCode(ByVal Character As Char,
                                  Optional ByVal KeyboardLayout As IntPtr = Nothing) As Short

    ' Get the Keycode of the character.
    Dim Keycode As Short =
        BitConverter.GetBytes(VkKeyScanEx(Character)).First

    Select Case Keycode

        Case Is <> 255 ' Character is found on the current KeyboardLayout.
            Return Keycode

        Case Else ' Character is not found on the current layour (Maybe is a diacritic character?)

            ' ****************************************************************************
            ' I want to perform the instructions below only if the character is diacritic.
            ' ****************************************************************************

            Dim s As String = CStr(Character).Normalize(System.Text.NormalizationForm.FormKD)

            For Each c As Char In s

                Select Case Globalization.CharUnicodeInfo.GetUnicodeCategory(c)

                    Case Globalization.UnicodeCategory.NonSpacingMark,
                         Globalization.UnicodeCategory.SpacingCombiningMark,
                         Globalization.UnicodeCategory.EnclosingMark

                        ' Do nothing.
                        Exit Select

                    Case Else ' Character is diacritic so we remove the diacritic and try to return the Keycode.
                        Return GetKeyCode(c, KeyboardLayout)

                End Select

            Next c

            ' ****************************************************************************
            ' I want to perform the instructions above only if the character is diacritic.
            ' ****************************************************************************

            Return 255 ' Character is not diacritic and the keycode can't be found.

    End Select

【问题讨论】:

  • 定义“变音符号”。字符“Ó”(U+00D3 拉丁大写字母 O WITH ACUTE)在任何正常定义下都不是变音符号。它可以被描述为包含一个变音符号。但是代码似乎规范化为规范化形式 KD,其中包括将“Ó”分解为“O”并结合急性。那么问题出在哪里?
  • @Jukka K. Korpela 我找到了计算分解字符数组长度的解决方案,感谢您的帮助。我指的是变音符号
  • 糟糕的计划。不仅仅是变音符号分解 - 考虑 1/2 和 1/4。
  • @Blam 是的,我会纠正,我发现效率不是 100%,我愿意接受所有建议/解决方案,感谢您的评论
  • 澄清一下,当我说变音符号时,我说的是变音符号和变音符号

标签: .net vb.net character-encoding character diacritics


【解决方案1】:

要知道章程是否是变音符号,最安全的办法是对其进行测试。

一种选择是遍历所有 Unicode 一次并将变音符号放入 HashSet。

如果您正在测试一个长字符串,则将整个字符串标准化一次。

如果您想要更广泛的映射,请考虑编码为 win1252。

【讨论】:

    猜你喜欢
    • 2010-10-12
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 2015-04-30
    • 2013-05-27
    相关资源
    最近更新 更多