Finding the position of a substring in a larger string

后端 未结 3 815
既然无缘
既然无缘 2020-12-11 23:46

I have created a function that should find the numerical position of the first character of a substring in a larger string. I am having some problems with the output and I a

3条回答
  •  失恋的感觉
    2020-12-12 00:16

    Your loop counter tests are incorrect: wrong upper limit and the limits are off by one. Note that the tests are actually not necessary as you exit both loops when hitting the '\0' terminators.

    Here is a simpler version:

    int findSubString(const char *original, const char *toFind) {
        for (size_t i = 0;; i++) {
            for (size_t j = 0;; j++) {
                if (toFind[j] == '\0') {
                    return i;
                }
                if (original[i + j] != toFind[j]) {
                    break;
                }
            }
            if (original[i] == '\0') {
                return -1;
            }
        }
    }
    

    There is a small advantage at computing the string lengths to reduce the number of comparisons in pathological cases such as findSubString("aaaaaaaaaaa", "aaaaaaaaaaaa");

    int findSubString(const char *original, const char *toFind) {
        size_t originalLength = strlen(original);
        size_t toFindLength = strlen(toFind);
    
        if (toFindLength <= originalLength) {
            for (size_t i = 0; i <= originalLength - toFindLength; i++) {
                for (size_t j = 0;; j++) {
                    if (toFind[j] == '\0') {
                        return i;
                    }
                    if (original[i + j] != toFind[j]) {
                        break;
                    }
                }
            }
        }
        return -1;
    }
    

提交回复
热议问题