简体   繁体   中英

find a char array in another char array in c

#include <iostream>
using namespace std;
int main ()
{
    char name[10];
    cin>>name;
    char str[] = "Thomas";
    char * pch;
    pch=strchr(name,str);
    if (pch!=NULL) {
        cout<<"Foud"<<endl;
    }

    return 0;
}

Hello, why i can't use 2 variables in strchr function, if you know how to search words in string

Use strstr

#include <iostream>
using namespace std;
int main ()
{
    char name[10];
    cin>>name;
    char str[] = "Thomas";
    char * pch;
    pch=strstr(name,str);
    if (pch!=NULL) {
        cout<<"Found"<<endl;
    }

    return 0;
}

The second argument to strchr is a character, expressed as an int. It will find the first instance of that character in the string.

char *strchr(const char *s, int c);

If you want to find a substring in a string use strstr,

char *strstr(const char *haystack, const char *needle);

strstr will point to the first substring or NULL if it's not found.

strchr is used to Locate first occurrence of character in string . strstr is used for Locate substring . See the references:

So, your program should look like:

#include <iostream>

using namespace std;

int main ()
{
    char name[10];
    cin>>name;
    char str[] = "Thomas";
    char *pch = strstr(name,str);
    if (pch != NULL) {
        cout<<"Found"<<endl;
    }

    return 0;
}

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