Last active
November 5, 2015 10:13
-
-
Save cloudwu/7d5d581714e6f9f8d21a to your computer and use it in GitHub Desktop.
make string to slices
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
struct sslice { | |
const char *ptr; | |
size_t sz; | |
}; | |
int | |
strslice(const char *s , size_t sz, const char * delim, struct sslice * result, int n) { | |
int i=0; | |
if (sz == 0) | |
sz = strlen(s); | |
while (i<n && sz>0) { | |
size_t j; | |
if (strchr(delim, *s)) { | |
++s; | |
--sz; | |
continue; | |
} | |
result[i].ptr = s++; | |
--sz; | |
for (j=0;j<sz;j++,s++) { | |
if (strchr(delim, *s)) { | |
break; | |
} | |
} | |
result[i].sz = j+1; | |
sz-=j; | |
++i; | |
} | |
return i; | |
} | |
#define MAXSLICE 10 | |
int | |
main() { | |
const char * a = "hello world foobar"; | |
struct sslice result[MAXSLICE]; | |
int n = strslice(a, 0, " \t\n\r", result, MAXSLICE); | |
int i; | |
for (i=0;i<n;i++) { | |
printf("%d %.*s\n", i, (int)result[i].sz, result[i].ptr); | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
好