When displaying instead of text, question marks and other characters, although on the intermediate output the character codes are correct. Help me please.

Console.Write("Введите код: "); string code = Console.ReadLine(); char[] code1 = code.ToCharArray(); Console.Write("Введите текст: "); string text = Console.ReadLine(); byte[] bytes = Encoding.GetEncoding(1251).GetBytes(text); int[] text1 = new int[text.Length]; for (int i = 0; i < text.Length; i++) text1[i] = bytes[i]; int[] text2 = new int[text.Length]; int b = 0; for (int a = 0; a < text.Length; a++) { if (bytes[a] >= 65 && bytes[a] <= 95 || bytes[a] >= 97 && bytes[a] <= 122 || bytes[a] >= 192 && bytes[a] <= 255 || bytes[a] == 168 || bytes[a] == 184 || bytes[a] >= 48 && bytes[a] <= 57) { if (b < code.Length) { text2[a] = text1[a] + Convert.ToInt32(code1[b].ToString()); b++; } else { b = 0; text2[a] = text1[a] + Convert.ToInt32(code1[b].ToString()); b++; } Console.Write(text2[a] + " "); } else { Console.Write(" "); } } Console.WriteLine(); for (int i = 0; i < text2.Length; i++) Console.Write(Convert.ToChar(text2[i])); Console.WriteLine(); 

program

  • five
    One , Two . Only the encoding is naturally your own ( Encoding.GetEncoding(1251) ). - EvgeniyZ
  • Show how these characters got into this array. - Alexander Petrov
  • Welcome to Stack Overflow in Russian! text information is better to attach as text: a) easier to read; b) can be copied; c) the search works. You can correct the question text by clicking below to edit the question text - aleksandr barakin
  • Use the class conversion method Encoding : Encoding.GetEncoding(1251).GetChars(bytesArray) . Note that it accepts an array of bytes as input. Accordingly, your int[] needs to be converted to byte[] . - Vlad
  • @AlexanderPetrov, added a program to the question, please see Alina Tereshchenko

1 answer 1

Lines in a unit. Namely, UTF-16. Symbols, respectively, too.

The string and char types of the .NET platform work only with Unicode and cannot use any other encodings.

This is where you correctly get the byte array containing the text encoded in win1251 using the Encoding class:

 string text = "как дела"; byte[] bytes = Encoding.GetEncoding(1251).GetBytes(text); 

After you have worked with the bytes in the desired encoding, you need to convert them back to Unicode.

The Convert.ToChar method will display exactly the Unicode character. But he believes that he received the Unicode code of this symbol as input. And you have the code win1251 .

Therefore, you need to use the Encoding class again:

 var byteArray = Array.ConvertAll(text2, n => (byte)n); var result = Encoding.GetEncoding(1251).GetString(byteArray); 

Please note that it takes an array of bytes , so first you need to convert your intov array.