简体   繁体   中英

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.

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.

You need to null terminate the a string so that it's a proper C string before calling strstr:

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. It is because strings in C need to be null terminated. 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. The null terminating 0 is used to mark the end of a string.

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)`. 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.

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