C#删除字符的重音符号
本文关键字:音符 符号 删除 字符 | 更新日期: 2023-09-27 17:58:47
如何在C#中将á
转换为a
?
例如:aéíúö
=>aeiuo
嗯,读过这些帖子[我不知道它们被称为儿科,所以我无法搜索]。
我想"放弃"除ñ
以外的所有药物
目前我有:
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();
但我认为有一种不那么"手动"的方法可以做到这一点?
如果您不想删除ñ,这是一个选项。它很快。
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));