S
S
sabotage_kyrazh2014-10-10 16:47:28
C++ / C#
sabotage_kyrazh, 2014-10-10 16:47:28

How to implement a function that looks for a substring in a string?

I'm taking an online course in C++ and again I'm in a stupor. The task reads like this:
Another common task with strings is to find a substring (some word or combination of characters) within another string. Implement a function that searches for a given substring in a string and returns the position of its first occurrence (remember that in C++ the convention is to count from 0) if the substring is found, or -1 if no such substring exists.
Sample Input:
Hello world!
ello
Sample Output:
1
Memory Limit: 256 MB
Time Limit: 5 seconds
Solve using pointers and arrays.
I still don’t understand C++ well, I didn’t manage to google anything sensible.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
G
GavriKos, 2014-10-10
@GavriKos

Google strcpy implementation. At least he can give some ideas. It is very difficult to explain the task "on the fingers" to a person with low knowledge of c / c ++. In short: you
take the first letter of the substring, go along the line, as soon as you find the letter, you start comparing element by element.

D
Dmitry, 2014-10-11
@mezastel

In general, it can be implemented with a couple of nested forloops: in the outer one, we go along the line, as soon as we find the 1st character, we make an inner loop in which we check that all the others match.

J
jcmvbkbc, 2014-10-10
@jcmvbkbc

google didn't work out anything

I should have started with a googling course.

M
mamkaololosha, 2014-10-10
@mamkaololosha

google Knuth-Morris-Pratt algorithm

M
maiq, 2014-10-17
@maiq

I sketched a function (possibly with errors), but I think the algorithm is clear:

int FindPattern(const char* arg_Str, const char* arg_Ptrn)
{
    int StrSz = strlen(arg_Str);
    int PSz = strlen(arg_Ptrn);
    if(StrSz < PSz || StrSz == 0 || PSz == 0)
        return -1;
    for(int StrIt = 0; StrIt <= StrSz - PSz; StrIt++)
    {
        if(arg_Str[StrIt] == arg_Ptrn[0])
        {
            bool IsBad = false;
            for(int PtrnIt = 1; PtrnIt < PSz; PtrnIt++)
                if(arg_Ptrn[PtrnIt] != arg_Str[StrIt + PtrnIt])
                {
                    IsBad = true;
                    break;
                }
            if(!IsBad) return StrIt;
        }
    }

    return -1;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question