【问题标题】:how to convert string of unicodes to the char?如何将unicode字符串转换为char?
【发布时间】:2011-05-03 06:09:40
【问题描述】:

我有一个文本文件,其中的 Unicode 集写为

"'\u0641'","'\u064A','\u0649','\u0642','\u0625','\u0644','\u0627','\u0647','\u0631' ,'\u062A','\u0643','\u0645','\u0639','\u0648','\u0623','\u0646','\u0636','\u0635','\u0633' ,'\u0641','\u062D','\u0628','\u0650','\u064E','\u062C','\u0626" "'\u0622'","'\u062E','\u0644','\u064A','\u0645"。

我打开文件并使用 readline 方法开始读取文件。我将上面的行显示为一行,现在我想将所有 Unicode 转换为 char,以便获得可读的字符串。我尝试了一些逻辑,但这不起作用我坚持将字符串“'\u00641'”转换为字符。

【问题讨论】:

  • 你从哪里得到这个文件?更改创建它的内容可能比解析它更简单。
  • 我们在我们的项目中使用这些文件。我没有得到你想说的
  • 但是这些文件是从哪里来的呢?是什么创造了它们?

标签: c# windows silverlight windows-phone-7


【解决方案1】:

您可以提取包含单个数字的字符串(例如使用 Regex),将 Int16.Parse 应用于每个字符串,然后将其转换为字符。

string num = "0641"; // replace it with extracting logic of your preference
char c = (char)Int16.Parse(num, System.Globalization.NumberStyles.HexNumber);

【讨论】:

  • A char 可以隐式转换为 ushort、int、uint、long、ulong、float、double 或 decimal。 (来自 MSDN)你可以写:ushort code = c;和变量 code 将保存 c 的 unicode 值。
  • 如果你想把它编码成一个类似于你输入文件的字符串,你应该写:String.Format("\\u{0:X4}", (ushort)c);跨度>
【解决方案2】:

您可以解析该行以获取每个 unicode 字符。要将 unicode 转换为可读字符,您可以这样做

char MyChar = '\u0058';

希望有帮助

【讨论】:

    【解决方案3】:

    如果你这样做会怎样:

    string codePoints = "\u0641 \u064A \u0649 \u0642 \u0625";
    
    UnicodeEncoding uEnc = new UnicodeEncoding();
    
    byte[] bytesToWrite = uEnc.GetBytes(codePoints);
    System.IO.File.WriteAllBytes(@"yadda.txt", bytesToWrite);
    
    
    byte[] readBytes = System.IO.File.ReadAllBytes(@"yadda.txt");
    string val = uEnc.GetString(readBytes);
    

    //丹尼尔

    【讨论】:

      猜你喜欢
      • 2018-09-18
      • 2019-04-19
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多