Skip to content

Instantly share code, notes, and snippets.

@hanxi
Forked from cloudwu/sslice.c
Created August 16, 2014 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hanxi/b65e8581eab60c142fb6 to your computer and use it in GitHub Desktop.
Save hanxi/b65e8581eab60c142fb6 to your computer and use it in GitHub Desktop.
#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 2
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);
}
while (n==MAXSLICE) {
const char * ptr = result[n-1].ptr+result[n-1].sz;
n = strslice(ptr, 0, " \t\n\r", result, MAXSLICE);
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