Remove accents from a text file

岁酱吖の 提交于 2021-01-28 18:30:45

问题


I have issues with removing accents from a text file program replaces characters with diacritics to ? Here is my code:

        private void button3_Click(object sender, EventArgs e)
        {

           if (radioButton3.Checked)
            {
                byte[] tmp;
                tmp = System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(richTextBox1.Text);
                richTextBox2.Text = System.Text.Encoding.UTF8.GetString(tmp);


            }

        }

回答1:


richTextBox1.Text = "včľťšľžšžščýščýťčáčáčťáčáťýčťž";            

string text1 = richTextBox1.Text.Normalize(NormalizationForm.FormD);

string pattern = @"\p{M}";
string text2 = Regex.Replace(text1, pattern, "�");

richTextBox2.Text = text2;

First normalize the string.
Then with a regular expression replace all diacritics. Pattern \p{M} is Unicode Category - All diacritic marks.




回答2:


Taken from here: https://stackoverflow.com/a/249126/3047078

static string RemoveDiacritics(string text)
{
  var normalizedString = text.Normalize(NormalizationForm.FormD);
  var stringBuilder = new StringBuilder();

  foreach (var c in normalizedString)
  {
    var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
    if (unicodeCategory != UnicodeCategory.NonSpacingMark)
    {
      stringBuilder.Append(c);
    }
  }

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

usage:

string result = RemoveDiacritics("včľťšľžšžščýščýťčáčáčťáčáťýčťž");

results in vcltslzszscyscytcacactacatyctz



来源:https://stackoverflow.com/questions/37069725/remove-accents-from-a-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!