简体   繁体   中英

How to find a char array in another one in c++?

I want to write a code to find a char array in another one and print out place(element) of first occur of first array. I wrote my own code and it works. But it "seems" kind of messy. Does anyone have better idea to rewrite this code?

"only strlen() is allowed. I need to write it by designing loops."

Here's the code

#include <iostream>
#include <string.h>

using namespace std;

const int len = 100;

int main() {
    int i, j, k, l;
    char a[len]="leonardo" , b[len]="nar";
    bool es1 = false, es2=false;

    i = 0;
    while(i < len && !es1)
    {
        j = 0;

        if(a[i] == b[j])
        {
            k = i+1;
            l = j;
            while (k < i+strlen(b) && !es2)
            {
                j = j+1;
                if (a[k] == b[j]) k = k+1;
                else es2 = true;
            }
            if (a[i+strlen(b)-1]==b[l+2] && !es2) es1 = true;
            else i = i+1;
        }
        else i= i+1;
    }

    cout << endl << "element: " << i;
    return 0;
}

By the way this not a real homework. I just make myself ready for a programming exam. I just find out that the code doesn't work fine if array b[] is shorter than 3 elements. So it seems the code needs major review!

The easy way to do it would be to use std::search :

auto it = std::search(a, a + 8, b, b + 3));

Here, it points to the beginning of the found sequence in a , or to std::end(a) if not found.

This looks like substring search algorithm. You can use any of the recognized algorithms like KMP .

Can you use a string instead of a char array? If so, you can use string::find.

http://www.cplusplus.com/reference/string/string/find/

bool bFound = strA.find(strB)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM