Write a function search which takes as input two char* strings. The first should be phrase, a phrase to search for, the second should be text, some text to scan through. It should return the number of times phrase appears in text. So search("be","to␣be␣or␣not␣to␣be") should return "2"
这个代码写出来其实并不难,比较难的点是如何实现效率会更高一些。这次尝试写了一个特别基础的版本,效率应该是比较低的,后续尝试进一步优化一下。
参考代码如下:
/* Write a function search which takes as input two char* strings. The first should be phrase, a phrase to search for, the second should be text, some text to scan through. It should return the number of times phrase appears in text. So search("be","to be or not to be") should return "2". */ int search(const char* f, const char* s) { int n = strlen(f); int len = strlen(s); int count = 0; for (int i = 0; i < len; i++) { bool result = true; for (int j = 0; j < n; j++) { if (*(s + i + j) != *(f + j)) { result = false; } } if (result) { count++; } } return count; } void testSearch() { const char* f = "be"; const char* s = "to be or not to be"; int count = search(f, s); std::cout << "search count is " << count << std::endl; ASSERT(count == 2); }