Advertisement
Guest User

Untitled

a guest
Aug 10th, 2017
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.84 KB | None | 0 0
  1. string eng = "qwertyuiop[]asdfghjkl;'zxcvbnm,.QWERTYUIOP{}ASDFGHJKL:"ZXCVBNM<>`~ёЁ";
  2. string ru = "йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮеЕеЕ";
  3. for (int i = 0; i < eng.Length; ++i)
  4. if (query.Contains(eng[i]))
  5. query = query.Replace(eng[i], ru[i]);
  6.  
  7. public sealed class Replacer
  8. {
  9. private readonly Dictionary<Char, Char> _dictionary;
  10.  
  11. public Replacer(String sourceSymbols, String targetSymbols)
  12. {
  13. if (sourceSymbols.Length != targetSymbols.Length)
  14. throw new NotSupportedException("sourceSymbols.Length != targetSymbols.Length");
  15.  
  16. Int32 count = sourceSymbols.Length;
  17.  
  18. Dictionary<Char, Char> dictionary = new Dictionary<Char, Char>(count);
  19. for (int i = 0; i < count; i++)
  20. dictionary.Add(sourceSymbols[i], targetSymbols[i]);
  21.  
  22. _dictionary = dictionary;
  23. }
  24.  
  25. public void FixCharacters(ref String query)
  26. {
  27. if (String.IsNullOrEmpty(query))
  28. return;
  29.  
  30. unsafe
  31. {
  32. Int32 index = query.Length - 1;
  33. fixed (Char* chPtr = query)
  34. {
  35. while (index >= 0)
  36. {
  37. Char oldChar = chPtr[index];
  38.  
  39. Char newChar;
  40. if (_dictionary.TryGetValue(oldChar, out newChar))
  41. chPtr[index] = newChar;
  42.  
  43. index--;
  44. }
  45. }
  46. }
  47. }
  48. }
  49.  
  50. static void Main(string[] args)
  51. {
  52. String eng = "qwertyuiop[]asdfghjkl;'zxcvbnm,.QWERTYUIOP{}ASDFGHJKL:"ZXCVBNM<>`~ёЁ";
  53. String rus = "йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮеЕеЕ";
  54.  
  55. Replacer replacer = new Replacer(eng, rus);
  56.  
  57. for (int i = 0; i < 10; i++)
  58. {
  59. String query = $"Hello World {i}";
  60.  
  61. replacer.FixCharacters(ref query);
  62.  
  63. Console.WriteLine(query); // "Руддщ Цщкдв"
  64. }
  65. }
  66.  
  67. public static class LangConversion
  68. {
  69. private static readonly Dictionary<char, char> engToRu = new Dictionary<char, char>();
  70.  
  71. static LangConversion()
  72. {
  73. var eng = "qwertyuiop[]asdfghjkl;'zxcvbnm,.QWERTYUIOP{}ASDFGHJKL:"ZXCVBNM<>`~ёЁ";
  74. var ru = "йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮеЕеЕ";
  75. for (var i = 0; i < eng.Length; i++)
  76. engToRu[eng[i]] = ru[i];
  77. }
  78.  
  79. public static string Fix(string str)
  80. {
  81. var sb = new StringBuilder();
  82. foreach (char c in str)
  83. {
  84. char fixedChar;
  85. sb.Append(engToRu.TryGetValue(c, out fixedChar) ? fixedChar : c);
  86. }
  87. return sb.ToString();
  88. }
  89. }
  90.  
  91. Исходный вариант: 6480мс
  92. Dictionary: 2330мс
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement