Skip to content

Instantly share code, notes, and snippets.

@alsamitech
Last active April 3, 2021 02:58
Show Gist options
  • Select an option

  • Save alsamitech/343b4fc586155416d487a9b96e170f2e to your computer and use it in GitHub Desktop.

Select an option

Save alsamitech/343b4fc586155416d487a9b96e170f2e to your computer and use it in GitHub Desktop.
Just making my own strtok in C...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __unix__
#include <unistd.h>
#endif
#define s_foreach(x, y)\ for(long unsigned int y=0;x[y]!=0;y++)
typedef long unsigned int strindex;
/*long unsigned int char_instances(char* bytes, char byte){
long unsigned int inst=0;
for(long unsigned int i=0; bytes[i]!=0;i++){
if(bytes[i]==byte){
inst++;
}
}
return inst;
}*/
long unsigned int char_instances(char* bytes, char* byte){
long unsigned int inst=0;
for(strindex i=0;bytes[i]!=0;i++){
for(long unsigned int xi=0;byte[xi]!=0;xi++){
if(bytes[i]==byte[xi]){
inst++;
}
}
}
return inst;
}
// returns a heap duplicate up to n bytes
char* strndupx(char* in, long unsigned int n){
char* new=malloc(n+1);
new[n]=0x0;
memcpy(new, in, n);
return new;
}
/*long unsigned int until_byte(char* bytes, long unsigned int n,char byte){
long unsigned int until;
for(until=0;until<n;until++){
if(bytes[until]==byte){
return until;
}
}
return n;
}*/
strindex until_byte(char* bytes, char* byte){
strindex until;
for(until=0;bytes[until]!=0;until++){
for(long unsigned int i=0;byte[i]!=0;i++){
if(bytes[until]==byte[i]){
return until;
}
}
}
return until;
}
char* onesep(char* in, char* sep, char** save_ptr){
long unsigned int until=until_byte(in, sep);
//printf("NICE: %lu %lu %s\n", strlen(in), until, in);
if(until==strlen(in))return 0;
*save_ptr=until;
return strndupx(in, until);
}
char* xsep(char* in, char* sep){
static char* save;
long unsigned int len;
if(in){
save=in;
len=0;
}
char* retval=onesep(save, sep, &len);
save+=len+1;
return retval;
}
char** onetokl(char* in, char* sep, long unsigned int* len){
//char** tok=(char**)malloc(sizeof(char*)+1);
char** tok=(char**)malloc(char_instances(in, sep)+1);
tok[0]=xsep(in, sep);
long unsigned int i;
for(i=1;tok[i-1]!=0;i++){
//tok=(char**)realloc(tok, i*sizeof(char*)+1);
tok[i]=xsep(0, sep);
}
*len=i;
return tok;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment