constk

Some_shit_searching_pattern_in_the_string

Feb 8th, 2020
170
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. int strStr(const char *text, const char *pattern);
  7. int strLen(const char *str);
  8. bool strCheck(const char *p, const char *pattern);
  9.  
  10. int main()
  11. {
  12. setlocale(0, "Russian");
  13. std::cout << "Programm started\n";
  14.  
  15. struct test {
  16. int ret_value;
  17. const char *text;
  18. const char *pattern;
  19. };
  20. test tests[] = {
  21. {0, "", ""}, //0
  22. {0, "a", ""}, //1
  23. {0, "a", "a"}, //2
  24. {-1, "a", "b"}, //3
  25. {0, "aa", ""}, //4
  26. {0, "aa", "a"}, //5
  27. {0, "ab", "a"}, //6
  28. {1, "ba", "a"}, //7
  29. {-1, "bb", "a"}, //8
  30. {0, "aaa", ""}, //9
  31. {0, "aaa", "a"}, //10
  32. {1, "abc", "b"}, //11
  33. {2, "abc", "c"}, //12
  34. {-1, "abc", "d"}, //13
  35. {-1, "a", "aa"}, //14
  36. {-1, "a", "ba"}, //15
  37. {-1, "a", "ab"}, //16
  38. {-1, "a", "bb"}, //17
  39. {-1, "a", "aaa"}, //18
  40. {-1, "aa", "aaa"}, //19
  41. {0, "aaa", "aaa"}, //20
  42. {0, "aaab", "aaa"}, //21
  43. {1, "baaa", "aaa"}, //22
  44. {1, "baaaa", "aaa"}, //23
  45. {1, "baaab", "aaa"}, //24
  46. {-1, "abd", "abc"}, //25
  47. {2, "ababc", "abc"}, //26
  48. {3, "abdabc", "abc"}, //27
  49. {-1, "", "a"}, //28
  50. {2, "asasaf", "asaf"}, //29
  51. {2, "ababac", "abac"} //30
  52. };
  53. for (int i = 0; i < sizeof(tests) / sizeof(tests[0]); ++i) {
  54. int ret = strStr(tests[i].text, tests[i].pattern);
  55. (tests[i].ret_value == ret) ? cout << "OK" : cout << "Failed";
  56. cout << " : " << i << " (" << tests[i].ret_value << " : " << ret << ")" << endl;
  57. }
  58.  
  59. system("pause");
  60. return 0;
  61. }
  62.  
  63. //находит первое вхождение в строке text некоторого шаблона pattern
  64. int strStr(const char *text, const char *pattern)
  65. {
  66. if (*pattern == '\0')
  67. return 0;
  68. else if (*text == '\0')
  69. return -1;
  70. int N = strLen(text);
  71. for (int i = 0; i < N; i++)
  72. {
  73. if (strCheck(text + i, pattern))
  74. return i;
  75. }
  76. return -1;
  77. }
  78.  
  79. //находит длину строки, не учитывая нулевой символ
  80. int strLen(const char *str)
  81. {
  82. int i = 0;
  83. while ( *(str + i) != '\0' )
  84. i++;
  85. return i;
  86. }
  87.  
  88. //проверяет соответствие некоторой части строки шаблону
  89. bool strCheck(const char *p, const char *pattern)
  90. {
  91. for (; *pattern != '\0'; pattern++)
  92. {
  93. if (*p != *pattern)
  94. return false;
  95. p++;
  96. }
  97. return true;
  98. }
RAW Paste Data