fork download
  1. #include <iostream>
  2. #include <cstring>
  3.  
  4. using namespace std;
  5.  
  6. const char* findx(const char* str, const char* strx)
  7. {
  8. if ( !(str && strx) ) {
  9. return nullptr;
  10. }
  11.  
  12. const char* found = nullptr;
  13. int s = 0, x = 0;
  14.  
  15. while (str[s] != '\0') {
  16. if (!found) {
  17. found = &str[s];
  18. }
  19.  
  20. if (strx[x] == '\0') {
  21. return found;
  22. }
  23.  
  24. if (str[s] != strx[x]) {
  25. found = nullptr;
  26. s = s-x +1;
  27. x = 0;
  28. }
  29. else {
  30. s++;
  31. x++;
  32. }
  33. }
  34.  
  35. return nullptr;
  36. }
  37.  
  38.  
  39. struct string_or_null {
  40. const char* str;
  41. };
  42.  
  43. ostream& operator << ( ostream& o, const string_or_null& fh) {
  44. if ( fh.str ) {
  45. o << '"' << fh.str << '"';
  46. }
  47. else {
  48. o << "nullptr";
  49. }
  50. return o;
  51. }
  52.  
  53. pair<int,int> test_findx() {
  54. struct test_t {
  55. const char* input;
  56. const char* subject;
  57. const char* expected;
  58.  
  59. test_t(const char* input, const char* subject, const int pos) {
  60. this->input = input;
  61. this->subject = subject;
  62. this->expected = ( pos == -1 ) ? nullptr : (input + pos);
  63. }
  64. } tests[] = {
  65. test_t("abc", "abc", 0),
  66. test_t("abcdef", "abc", 0),
  67. test_t("ababac", "abac", 2),
  68. test_t("ababac-----", "abac", 2),
  69.  
  70. test_t("abc", "xyz", -1),
  71. test_t("abc", "", -1),
  72. test_t("", "", 0),
  73. test_t("", "a", -1),
  74.  
  75. // ...
  76. };
  77.  
  78.  
  79.  
  80. int total = sizeof(tests)/sizeof(tests[0]);
  81. int failed = 0;
  82. for ( const auto& test : tests ) {
  83. int test_no = &test - tests;
  84. const char* result = findx(test.input, test.subject);
  85.  
  86. if ( result != test.expected ) {
  87. failed ++;
  88. cout << "Test #" << test_no
  89. << " failed: " << string_or_null{test.subject}
  90. << " in " << string_or_null{test.input}
  91. << ", expected " << string_or_null{test.expected}
  92. << ", got " << string_or_null{result}
  93. << endl;
  94. }
  95. }
  96.  
  97. return {total, failed};
  98. }
  99.  
  100.  
  101. int main() {
  102. pair<int,int> result = test_findx();
  103. cout << "Failed " << result.second << " of " << result.first << " tests." << endl;
  104. }
  105.  
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
Test #0 failed: "abc" in "abc", expected "abc", got nullptr
Test #2 failed: "abac" in "ababac", expected "abac", got nullptr
Test #5 failed: "" in "abc", expected nullptr, got "abc"
Test #6 failed: "" in "", expected "", got nullptr
Failed 4 of 8 tests.