Trouble with my string function

Hello, I am writing my own string library as sort of an exercise and I am doing rarther well so far. I am a bit stuck on a function which locates the occurance of a substring within a larger string. Here is my function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int locate_substring_occurrence(string_c s_stringToSearch, string_uc s_substring, int i_occurrenceNumber)
{
    int i_substringLength = (sizeof(s_substring) / sizeof(const char)) - 1;
    int i_substringSearchPosition = 0;
    for(int i = 0; i < 16384; i ++)
    {
        if(s_substring[i_substringSearchPosition] == s_stringToSearch[i])
        {
            if(i_substringSearchPosition < i_substringLength)
            {
                i_substringSearchPosition ++;
            }
            else
            {
                return i - i_substringLength;
            }
        }
    }
    return -1;
}
(Ignore parameter 3, its not used at the moment) Now, it appears to work fine with substrings over 3 characters long, if I test it with locate_substring_occurrence("hojocina eliphaa deaketyed cib tiuzi", "deaketyed", 1) I get an output of 17 as expected, but if I try it with the substring as "cib" I get an output of 33. I have no idea why substrings less than 4 characters long yield incorrect results. I have tried re-arranging the code and I pretended to be a compiler myself and wrote the results down on a piece of paper but I still couldent figure out why I was getting this error. Btw, string_c and string_uc are typedefs;
1
2
typedef const char string_c[16384];
typedef const char string_uc[];


Thankyou
Last edited on
int i_substringLength = (sizeof(s_substring) / sizeof(const char)) - 1;
This will not give you the length of the string. s_substring is a pointer so sizeof(s_substring) gives you the size of a pointer.

Oh, thankyou for that :) So how would I get the length of the string?
Pass it as an argument to the function.

EDIT: If your strings are null terminated you can also use a function such as std::strlen to get the length.
Last edited on
Okay thankyou, its working now :)
Topic archived. No new replies allowed.