# Thread: how to compare char array with one char?

1. ## how to compare char array with one char?

for example:

char buff = "123456789";
char buff2 = "2";

how can i compare with the char"2" with the string above?

cos when i use strcmp(buff[i],buff2); there will be errors. 2. >>strcmp(buff,buff2); 3. ## thank you hammer for helping

thank you hammer, i am sorry that i should have asked the question more precisely.

mmmmm here is the situation:

char = "000000000000000000ham001000000000"
assuming you dun know where "ham" is....and...not every string contains "ham"(cos the data is from the com port, and the position of "ham" is different every time.)

what i wanna do is to know where is the ham, and get the "1" out.

cos i am thinking of if i can know the postion of "h", then i know where is the "1".(assume the one is always two "0"s after "m")

sorry hammer 4. ## thank you very much

thank you so much.

and i would like to ask is....what will it return?
would you please explain a bit more? 5. ## i think i understand it....

thank you very much!!

i have found it in the MSDN.... 6. I'm sure this will provoke future response if I am wrong, and then we'll both learn.

strstr takes two strings, the first is the string to search and the second is the string to search for. The return value of strstr is a pointer to the first letter of the first instance of the substring being sought. If the substring isn't found, then p will be NULL. If the substring is found, then, given your assurance that the string will always be "ham001" and not just "ham", the 1 will occur at p + 5. Now, my only question is whether the p + 5 correlates with p. If p were to be interpretted as a string that started at p and extends to the end of buff, then the answer would be that p + 5 is equivalent to p; I'm just not sure of that.

The real question, though is how do you use the information, now that you know the substring occurs at least once in the search string? Knowing that it exists may be enough, but I suppose you might want to know where p is relative to some spot in the search string. Then, since you know 1 is a p + 5, you will know where 1 is.

To do that you can subtract the address at the start of the search string, &buff or just buff, from p. Since each char takes up 4 bits of memory you can then determine how far away from the start of the search string the 1 occurs. 7. ## Comparing single char's

Hi,

The program below searches for a single char in a string.

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char s = "12345678922543329";

char a = '2'; // NOTE single quotes
int x;

for(x = 0; x < strlen(s); ++x)
{

if(s[x] == a) // could use '2' instead of the char a
{
printf("\nMatch at %d",x);
}

}

getch();
return 0;
} Popular pages Recent additions 