简体   繁体   English

在C中的另一个char数组中找到一个char数组

[英]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 您好,为什么我不能在strchr函数中使用2个变量,如果您知道如何在字符串中搜索单词

Use strstr 使用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. strchr的第二个参数是一个字符,表示为一个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, 如果要在字符串中查找子字符串,请使用strstr,

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

strstr will point to the first substring or NULL if it's not found. strstr将指向第一个子字符串,如果找不到,则为NULL。

strchr is used to Locate first occurrence of character in string . strchr用于Locate first occurrence of character in string strstr is used for Locate substring . strstr用于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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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