Вопрос

Im trying to write a function that returns the index of the first occurence of a substring within a string.

like searching skyscraper for 'ysc' would return 2.

It seems like strstr is doing its job because after the while loop it outputs the correct first char of the substring but it isnt counting correctly and returning the correct int.

I may have this set up wrong as I am passing an array to the function and got a lot of errors trying to use nested loops so I tried for a while loop instead which compiles but isnt outputting correctly.

Im still fairly new to pointers and passing them as arguements so there may be an issue there.

anything helps!

int findSubstring(char *s, char substring[])
{   
    int j = 1;
    char* strPtr = NULL;

    while (strPtr == NULL)
    {
        strPtr = strstr(s, substring);
        if (strPtr != NULL)
            break;
        j++;
    }

    cout << *strPtr << endl;
    cout << "The substring begins at element: " << j << endl;
    return j;
}
Это было полезно?

Решение

What about just using pointer arithmetic?

int findSubstring(char *s, char substring[])
{   
    char* strPtr = strstr(s, substring);
    if (strPtr != NULL)
    {
        return (int)(strPtr - s);
    }
    else
    {
        return -1;  //no match
    }
}

Другие советы

Fix yours as, refer this example:

 int findSubstring(char *s, char substring[]) 
{
    char* pos = strstr(s, substring);
    if(pos) 
     return (int)(pos - s);
    else -1;
}

And you're using C++, so, why not std::string ?

 int findSubstring(const std::string& s, const std::string& substring)
{   

std::size_t j =s.find(substring);
return ( j!=std::string::npos) ? j :-1;
}

You seem to be over complicating the task, since you're using C++ you should be using std::string::find.

std::string s = "skyscraper";
std::size_t pos = s.find("ysc");
if( pos != std::string::npos )
    std::cout << "ysc found at " << pos << "\n";
else
    std::cout << "ysc not found" << "\n";
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top