Alibaba interview questions: implement the Char ** StrToK (const char * S1, const char * S2) function, Alibaba strtok
Implementation function: Char ** StrToK (const char * S1, const char * S2)
Function: After S2 truncates the S1 string, It outputs the truncated string. For example, S1 = abcdefg, S2 = be, returns the three strings a, cd, and fg with a pointer to the pointer.
#include <stdio.h>#include <string.h>#include <stdlib.h>char **str2tok(const char *s1,const char *s2){ int i=0,j=0; int hash[256]={}; char *q=s1,*p=s1; char **res = (char**)malloc(sizeof(char*)*strlen(s1)); while(*s2) { hash[*s2]=1; s2++; } while(*p) { if(hash[*p] != 1) { p++; i++; } else { if(i==0) { p++; q=p; } else { char *tmp=(char*)malloc(sizeof(char)*i+1); snprintf(tmp,i,"%s",q); tmp[i]='\0'; res[j]=tmp; j++; i=0; p++; q=p; } } } if(i>0) { char *tmp=(char*)malloc(sizeof(char)*i+1); snprintf(tmp,i,"%s",q); tmp[i]='\0'; res[j]=tmp; j++; } res[j]=NULL; return res;}int main(void){ char *s1="abcdef"; char *s2="be"; char **res=str2tok(s1,s2); while(*res) { printf("%s,",*res); res++; } printf("\n"); return 0;}
Strtok Function
1. The function definition in c99 is:
Char * strtok (char * restrict s1, const char * restrict s2 );
Your so-called sentence may refer to the unavailability of char *, because it must be defined as const char *, and char [] is referenced as const char * due to the array feature *
For example, you define
Char str [20];
Char * p;
So
P ++ is valid, and the pointer reference address is changed.
Str ++ or invalid, which is equivalent to const char *
2. After the string is split for the first time, the separator is converted into a space. If the first parameter is set to NULL, each sub-string is returned in order and one is returned for each call, so the token will change. If no substring exists, NULL is returned.
Supplement:
Yes, unless the first parameter is not NULL, it will start again.
Char * strtok_r (char * s, const char * delim, char ** ptrptr); what is char ** ptrptr?
Most * _ r functions are basically reentrant functions. They can also be considered thread-safe functions. For example, strtok uses delim to cut s strings, each time the newest cut result is returned, for this function, each execution must know the last execution result. Therefore, each execution must save the status of this execution, for a function without _ r, static variables are used in the function, but errors may occur when multithreading occurs. Therefore, the address pointed to by ptrptr stores the call results of the current thread, in this way, no errors will occur when different threads call this function. You do not need to know the specific content, but just need to input a valid address.