《quantitative finance with cpp》阅读笔记22---查询字符串出现的次数
作者:yunjinqi   类别:    日期:2024-01-01 22:56:38    阅读:427 次   消耗积分:0 分    

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);
}


版权所有,转载本站文章请注明出处:云子量化, http://www.woniunote.com/article/387
上一篇:《quantitative finance with cpp》阅读笔记21---极坐标转换成直角坐标
下一篇:《quantitative finance with cpp》阅读笔记23---写二元看涨期权、二元看跌期权类,并改写看跌期权以便继承PathIndependentOption类