Wednesday, April 3, 2013

Attention for strtok() in C



Head file:#include<string.h>
Function prototype: char * strtok(char *s,const char *delim);
Description:divide string s into pieces according to string delim
  1. strtok() scans s, if it finds the current character is in delim(delim is a character set), then strtok() replaces current character with '\0'[this means string s is changed]
  2. At first, strtok() needs s as a parameter, but then, we can call strtok() by set s as NULL, strtok() will return the next string point(If there is no strings any more, strtok() will return NULL).
#include<stdio.h>
#include<string.h>
int main()
{
    char s[]="ab-c656f;gh,i-jkl;mnop;54;fdfdz";
    char *delim="-, ";
    char *p;
    printf("%s ";strtok(s,delim));
    //printf("%s ";s); //s is changed
    while((p=strtok(NULL,delim)))
    {
        printf("%s ",p);
    }
    printf("\n");
    return 0;
}

-----------------------My work for Strtok()-----------------

int numOfParametersCheck(const uchar *str,const int num)
{
    int numParameters=0;
uchar cpyStr[MAXLEN_CMD];
strcpy(cpyStr,str);//I duplicate a new string 
strtok(cpyStr," ");
while(strtok(NULL," ")!=NULL)
{
   numParameters++;
   if(numParameters>num)
   {
       printf("Cmd should have %d parameter!\n\n",num);
            return 0;
   }
}
if(numParameters==num)
{
   return 1;
}
else  //numParameters<num
{
        printf("Cmd should have %d parameter!\n\n",num);
   return 0;
}
}

No comments:

Post a Comment