简体   繁体   English

如何使用 C 中的 strstr() function 检查字符串中是否存在字符

[英]How to check whether char exists in string using strstr() function in C

This must be a simple problem about char data type and pointers.这一定是一个关于 char 数据类型和指针的简单问题。

void main() {

    const char* a;
    char character = 65;
    a = &character;

    printf("%c \n", character); // PRINTS 'A' AS EXPECTED

    if (strstr("ABC", a)) { 
        printf("found \n");
    }
    else {
        printf("not found\n"); // goes into else
    }
}

I don't understand why it doesn't go into first if statement.我不明白为什么它没有 go 进入第一个 if 语句。

You need to null terminate the a string so that it's a proper C string before calling strstr:在调用 strstr 之前,您需要 null 终止a字符串,以便它是正确的 C 字符串:

Any of the following:以下任何一项:

if (strstr("ABC", "A"))
{
    // found
}

Or或者

char a[2] = {'A', '\0'};
if (strstr("ABC", a))
{
    // found
}

Or或者

const char* a = "A";
if (strstr("ABC", a))
{
    // found
}

a is not a string. a不是字符串。 It is because strings in C need to be null terminated.这是因为 C 中的字符串需要 null 终止。 By null terminated, I mean it's last element should be 0. It's so that when you pass strings to functions, then he functions can know when the string ends.通过 null 终止,我的意思是它的最后一个元素应该是 0。这样当你将字符串传递给函数时,他的函数可以知道字符串何时结束。 The null terminating 0 is used to mark the end of a string.以 0 结尾的 null 用于标记字符串的结尾。

You need to do:你需要做:

char *a;
char character[2];
character[0] = 'A'; //Don't use 65. ASCII isn't the only encoding
character[1] = '\0';
a = character; //a is useless, you can pass character directly

Now, pass it: strstr("ABC", a)`.现在,传递它:strstr("ABC", a)`。 The above method is very bad, don't use it.上面的方法很差,不要用。 Do one of these in practice:在实践中执行以下操作之一:

char a[2] = "A"; //This will null terminate for you
//OR
const char *a = "A";
//OR
char a[2] = {'A', '\0'};

Using any one of these declarations, strstr should work.使用这些声明中的任何一个, strstr应该可以工作。

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

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