How to convert from unicode to ASCII

2020-02-11 04:47发布

Is there any way to convert unicode values to ASCII?

标签: c#-3.0
5条回答
家丑人穷心不美
2楼-- · 2020-02-11 05:02

To simply strip the accents from unicode characters you can use something like:

string.Concat(input.Normalize(NormalizationForm.FormD).Where(
  c => CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark));
查看更多
相关推荐>>
3楼-- · 2020-02-11 05:04

Technically, yes you can by using Encoding.ASCII.

Example (from byte[] to ASCII):

// Convert Unicode to Bytes

byte[] uni = Encoding.Unicode.GetBytes("Whatever unicode string you have");

// Convert to ASCII

string Ascii = Encoding.ASCII.GetString(uni);

Just remember Unicode a much larger standard than Ascii and there will be characters that simply cannot be correctly encoded. Have a look here for tables and a little more information on the two encodings.

查看更多
贼婆χ
4楼-- · 2020-02-11 05:07

Well, seeing as how there's some 100,000+ unicode characters and only 128 ASCII characters, a 1-1 mapping is obviously impossible.

You can use the Encoding.ASCII object to get the ASCII byte values from a Unicode string, though.

查看更多
放荡不羁爱自由
5楼-- · 2020-02-11 05:14

This workaround might better suit your needs. It strips the unicode chars from a string and only keeps the ASCII chars.

byte[] bytes = Encoding.ASCII.GetBytes("eéêëèiïaâäàåcç  test");
char[] chars = Encoding.ASCII.GetChars(bytes);
string line = new String(chars);
line = line.Replace("?", "");
//Results in "eiac test"

Please note that the 2nd "space" in the character input string is the char with ASCII value 255

查看更多
forever°为你锁心
6楼-- · 2020-02-11 05:16

You CAN'T convert from Unicode to ASCII. Almost every character in Unicode cannot be expressed in ASCII, and those that can be expressed have exactly the same codepoints in ASCII as in UTF-8, which is probably what you have. Almost the only thing you can do that is even close to the right thing is to discard all characters above codepoint 128, and even that is very likely nowhere near what your requirements say. (The other possibility is to simplify accented or umlauted letters to make more than 128 characters 'nearly' expressible, but that still doesn't even begin to actually cover Unicode.)

查看更多
登录 后发表回答