Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

string - How to replace special characters with their equivalent (such as " á " for " a") in C#?

I need to get the Portuguese text content out of an Excel file and create an xml which is going to be used by an application that doesn't support characters such as "?", "á", "é", and others. And I can't just remove the characters, but replace them with their equivalent ("c", "a", "e", for example).

I assume there's a better way to do it than check each character individually and replace it with their counterparts. Any suggestions on how to do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 accents from the text, filters them and creates a new string. Combining diacritics are in the Non spacing mark unicode category.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...