1

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,

Sunscreen
  • 3,452
  • 8
  • 34
  • 40

1 Answers1

2

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • oh i thought that strcmp needed to secure space for each variable, I did not know that even pointers work. Thanks. – Sunscreen Feb 26 '15 at 14:23