C#从角色中删除重音?

时间:2011-06-08 22:59:26

标签: c#

如何在C#中将á转换为a

例如:aéíúö => aeiuo

嗯,看过那些帖子[我不知道他们被称为diatrics,所以我无法搜索那个]。

我想“删除”除“ñ

之外的所有语量

目前我有:

public static string RemoveDiacritics(this string text)
{
    string normalized = text.Normalize(NormalizationForm.FormD);
    var sb = new StringBuilder();

    foreach (char c in from c in normalized
                       let u = CharUnicodeInfo.GetUnicodeCategory(c)
                       where u != UnicodeCategory.NonSpacingMark
                       select c)
    {
        sb.Append(c);
    }

    return sb.ToString().Normalize(NormalizationForm.FormC);
}

ñ排除在外的最佳方式是什么?

我的解决方案是在foreach之后执行以下操作:

var result = sb.ToString();

if (text.Length != result.Length)
    throw new ArgumentOutOfRangeException();

int position = -1;
while ((position = text.IndexOf('ñ', position + 1)) > 0)
{
    result = result.Remove(position, 1).Insert(position, "ñ");
}

return sb.ToString();

但我认为有一种较少的“手动”方式可以做到这一点吗?

1 个答案:

答案 0 :(得分:1)

如果您不想删除ñ,这是一个选项。很快。

    static string[] pats3 = { "é", "É", "á", "Á", "í", "Í", "ó", "Ó", "ú", "Ú" };
    static string[] repl3 = { "e", "E", "a", "A", "i", "I", "o", "O", "u", "U" };
    static Dictionary<string, string> _var = null;
    static Dictionary<string, string> dict
    {
        get
        {
            if (_var == null)
            {
                _var = pats3.Zip(repl3, (k, v) => new { Key = k, Value = v }).ToDictionary(o => o.Key, o => o.Value);
            }

            return _var;
        }
    }
    private static string RemoveAccent(string text)
    {
        // using Zip as a shortcut, otherwise setup dictionary differently as others have shown
        //var dict = pats3.Zip(repl3, (k, v) => new { Key = k, Value = v }).ToDictionary(o => o.Key, o => o.Value);

        //string input = "åÅæÆäÄöÖøØèÈàÀìÌõÕïÏ";
        string pattern = String.Join("|", dict.Keys.Select(k => k)); // use ToArray() for .NET 3.5
        string result = Regex.Replace(text, pattern, m => dict[m.Value]);

        //Console.WriteLine("Pattern: " + pattern);
        //Console.WriteLine("Input: " + text);
        //Console.WriteLine("Result: " + result);

        return result;
    }

如果要删除ñ,则更快的选项是: Encoding.ASCII.GetString(Encoding.GetEncoding("Cyrillic").GetBytes(text));