简体   繁体   中英

Search for string in char array

I'm attempting to search for a string in a character array whereby the string to be identified is UCAST and whereby the character array is as follows:

analysis_buffer[0] = \n;
analysis_buffer[1] = U;
analysis_buffer[2] = C;
analysis_buffer[3] = A;
analysis_buffer[4] = S;
analysis_buffer[5] = T;
analysis_buffer[6] = \r;

The code I executed to attempt the search procedure is as follows:

            constant char str[] = "UCAST";
        char* pch = strstr(analysis_buffer,str);

        if (pch!=NULL) {
            printf("found at %d\n", pch - analysis_buffer + 1);

            pch = strstr(pch+1, analysis_buffer);
        } else {
            printf("pch :%s\n", pch);
        }

NOTE: analysis_buffer is the array I described above.

The problem I'm encountering is that the strstr bit amounts to NULL while it shouldn't. Any ideas?

I've had a look at the following links on stackoverflow for help:

Does char array contain string?

How to search a string in a char array in C?

THANKS

The code is incorrect as the array is one element too short for the initializer:

char str[5] = "UCAST";

due to implicit null character added to all string literals. From section 6.4.5 String literals point 5 of the C99 standard:

In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literal. ...

Possible fixes:

  • allow the deduction of the required array size:

     char str[] = "UCAST"; 
  • use a const char* as it is unrequired for str to be modified:

     const char* str = "UCAST"; 

Note that the string being searched ( analysis_buffer in this case) must be null terminated also. From the posted code it is not apparent that this is happening.

Additionally, the final printf() statement is incorrect as the format specifier is %c but the argument ( pch ) type is char* . Normally, either use %s and use pch or use %c and *pch BUT pch is NULL in this branch of the if so it cannot used in the printf() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM