Skip to main content
Visitor II
September 14, 2020
Question

search a char array within an other char array

  • September 14, 2020
  • 2 replies
  • 5456 views

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

    This topic has been closed for replies.

    2 replies

    Graduate II
    September 14, 2020

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

    AlaAuthor
    Visitor II
    September 15, 2020

    dear clive1

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

    Technical Moderator
    September 15, 2020

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