Search code examples
cc89

use char* to compare with a value on string


Hi I use the function strtok to split an array as follows:

char str[] ="one11;one2";
char* pch;
pch = strtok (str,";");
while (pch != NULL)
    pch = strtok(NULL, ";");

Now I need to compare my pointer pch with a specific value, let's say:

if (pch == "one11")
  // do this

Although I am getting the first part of the string, in this case 'one11' the comparison fails. Is there a way to compare these two things?

Thanks,


Solution

  • To compare strings use standard function strcmp declared in header <string.h>. For example

    #include <string.h>
    
    //..
    char str[] ="one11;one2";
    char* pch;
    pch = strtok (str,";");
    while ( pch != NULL && strcmp( pch, "one11" ) != 0 )
        pch = strtok(NULL, ";");
    

    If the first string is less than the second string the function returns a negative value. If strings are equal then the function returns 0. And if the first string is greater than the second string the function returns a positive value.