Skip to content

Instantly share code, notes, and snippets.

@cloudwu
Last active November 5, 2015 10:13
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save cloudwu/7d5d581714e6f9f8d21a to your computer and use it in GitHub Desktop.
Save cloudwu/7d5d581714e6f9f8d21a to your computer and use it in GitHub Desktop.
make string to slices
#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;
}
@hanxi
Copy link

hanxi commented Aug 16, 2014

@pallove
Copy link

pallove commented Aug 16, 2014

%.*,以前还没用过。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment