Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

c - Finding the position of a substring in a larger string

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 am not too sure why. These problems include -1 being returned every single time instead of the integer position of the substring. I have debugged and cannot trace where the function goes wrong.

This is how the function should perform: If my string is "The dog was fast" and I am searching for the substring "dog", the function should return 4. Thanks to chqrlie for help with the loop.

Here is the function:

int findSubString(char original[], char toFind[]) {

    size_t i, j;
    int originalLength = 0;
    int toFindLength = 0;

    originalLength = strlen(original) + 1;
    toFindLength = strlen(toFind) + 1;

    for (i = 0; i < toFindLength + 1; i++) {
        for (j = 0; j < originalLength + 1; j++) {
            if (toFind[j] == '') {
                return i;
            }
            if (original[i + j] != toFind[j]) {
                break;
            }
        }
        if (original[i] == '') {
            return -1;
        }
    }
}

The function parameters cannot be modified, this is a requirement. Any help appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your loops are reversed. The outer loop should walk positions from zero to originalLength, inclusive; the nested loop should walk positions from zero to toFindLength, inclusive.

Both originalLength and toFindLength should be set to values returned by strlen, not strlen plus one, because null terminator position is not a good start.

Finally, you are returning -1 from inside the outer loop. This is too early - you should be returning -1 only after you are done with the outer loop as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...