开发者

Comparing buffer with a C String [duplicate]

This question already has answers here开发者_运维技巧: Closed 10 years ago.

Possible Duplicate:

How to compare pointer to strings in C

How to compare the characters in a buffer with a string?


By buffer, I assume its not NULL terminated. Then you can not use strcmp, instead you can use strncmp.


Assuming, the buffer is an array of characters. You can compare character by character. Example -

char buffer[] = { 'a','b','c' };
char* str = "b";

int i=0;
while( i<3 )
{
    if( buffer[i] == *str )
        printf("\n Equal \n" );
    else
        printf("\n Not Equal \n" );

    ++i;
}

The above code should give you basic idea of how to implement. Results : IdeOne

Things you need to think of to answer the question -

  • What if the value pointed by str is "abc"?
  • What if the entire buffer needs to be compared to value pointed by char* ( i.e., buffer is equal to value pointed by char* ?


Something that throws a lot of people off at first is that strcmp returns 0 if the strings match, so you usually use something like if (!strcmp(buffer, "change"))


int strcmp ( const char *s1, const char *s2 );

Try this. It will help you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜