Comparing buffer with a C String [duplicate]
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 bychar*
?
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.
精彩评论