2023年9月1日 星期五

[C][string] strtok/strtok_r 字串切割

字串切割 
string tokenization

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    const char * const str = "MAC-:AA-BB-CC-DD-EE-FF";
    const char * const delimitation = "-:";
    char * const dupstr = strdup(str);
    char *saveptr = NULL, *substr = NULL;
    int i = 0;

    printf("original: %s (%p)\n", dupstr, dupstr);
    
    substr = strtok_r(dupstr, delimitation, &saveptr);

    do {
        printf("#%d after parsing: %s (%p)\n", i++, substr, substr);
        substr = strtok_r(NULL, delimitation, &saveptr);
    } while (substr);
    
}

/*
[Result]
original: MAC-:AA-BB-CC-DD-EE-FF (0x55f73e1e42a0)
#0 after parsing: MAC (0x55f73e1e42a0)
#1 after parsing: AA (0x55f73e1e42a5)
#2 after parsing: BB (0x55f73e1e42a8)
#3 after parsing: CC (0x55f73e1e42ab)
#4 after parsing: DD (0x55f73e1e42ae)
#5 after parsing: EE (0x55f73e1e42b1)
#6 after parsing: FF (0x55f73e1e42b4)
*/


[C][string] strstr/strchr用法

在字串中找特定字

eq,
在”ABCDEF”中找”CD” → 用strstr,不能用strchr,記憶體會壞掉
在”ABCDEF”中找’C’ → 用strchr,也可以用strstr

[C][string] sscanf用法

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
   int day, year;
   char weekday[20], month[20], tmp[100];

   strcpy(tmp, "Saturday March aaa 25 1999");
   
   /*"%*s" means ignore aaa*/
   sscanf(tmp, "%s %s %*s %d %d", weekday, month, &day, &year);

   printf("%s %d %d %s", month, day, year, weekday);
    
   return(0);
}

/*
[Result]
March 25 1999 Saturday
*/
%*s 表示可以忽略字串的中aaa