[ACCEPTED]-How to replace special characters with their equivalent (such as " á " for " a") in C#?-character
Accepted answer
You could try something like
var decomposed = "áéö".Normalize(NormalizationForm.FormD);
var filtered = decomposed.Where(c => char.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark);
var newString = new String(filtered.ToArray());
This decomposes 3 accents from the text, filters them and 2 creates a new string. Combining diacritics 1 are in the Non spacing mark unicode category.
string text = {text to replace characters in};
Dictionary<char, char> replacements = new Dictionary<char, char>();
// add your characters to the replacements dictionary,
// key: char to replace
// value: replacement char
replacements.Add('ç', 'c');
...
System.Text.StringBuilder replaced = new System.Text.StringBuilder();
for (int i = 0; i < text.Length; i++)
{
char character = text[i];
if (replacements.ContainsKey(character))
{
replaced.Append(replacements[character]);
}
else
{
replaced.Append(character);
}
}
// 'replaced' is now your converted text
0
For future reference, this is exactly what 1 I ended up with:
temp = stringToConvert.Normalize(NormalizationForm.FormD);
IEnumerable<char> filtered = temp;
filtered = filtered.Where(c => char.GetUnicodeCategory(c) != System.Globalization.UnicodeCategory.NonSpacingMark);
final = new string(filtered.ToArray());
The perform is better with this solution:
string test = "áéíóúç";
string result = Regex.Replace(test .Normalize(NormalizationForm.FormD), "[^A-Za-z| ]", string.empty);
0
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.