cancel
Showing results for 
Search instead for 
Did you mean: 

search a char array within an other char array

Ala
Senior

hi everyone

I'm trying to search for a certain char array(say char Temp[]) within a lager array in this case, char Rcv[500]. here is my code

int scanRcv(char *Temp){
int ii=0;	
for(int i=0;i<RcvLength;i++){
while(Rcv[i]==Temp[ii]){
ii++;
if(ii==strlen(Temp)) 
{
return 1;}
else
{return 0;}
ii=0;
}	
}

but I don't know why it doesn't work and does not return 1, though I think the code works....

I also tried this code too but it didn't work either

int scanRcv(char *Temp){
if(strstr(Rcv,Temp)!=0)
{
		return 1;
}
else
{
		return 0;
}	
}

please help

3 REPLIES 3

>>but I don't know why it doesn't work and does not return 1, though I think the code works....

Clearly it doesn't work. You reset the index at every iteration of the inner loop. You exit immediately on the first match/mismatch.

Get the indentation presented more clearly.

Get the logic worked out.

Make some assorted test cases, and show how the function gets used in normal operation, and that it recognizes the strings.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..

dear clive1

I just reset the index after I find the entire match (i.e. ii==strlen(Temp)). what's wrong with that?

PatrickF
ST Employee

As strstr() return a pointer, you should test for a null pointer in case string is not found.

e.g. if(strstr(Rcv,Temp)!=NULL) ....

In order to give better visibility on the answered topics, please click on 'Accept as Solution' on the reply which solved your issue or answered your question.