使用字符类:
#include <stdio.h>
int main(int argc, const char **argv) {
char s1[10], s2[10];
const char *str = "word1,word2";
sscanf(str, "%[^,],%s", s1, s2);
printf("%s -- %s\n", s1, s2);
return 0;
}
或者你可以更具体:
sscanf(str, "%[^,],%[^,]", s1, s2);
这也将捕获空白s2
要拆分多个字符,您可以使用strstr
:
#include <stdio.h>
#include <string.h>
int main(int argc, const char **argv) {
const char *str = "word1fooword2fooword3", *foo = "foo", *ptr;
const char *eofstr = str;
for (ptr = str; eofstr; ptr = eofstr + strlen(foo)) {
char word[10];
eofstr = strstr(ptr, foo);
if (eofstr) {
size_t len = eofstr - ptr;
strncpy(word, ptr, len);
word[len] = 0;
printf("%s\n", word);
} else {
strcpy(word, ptr);
printf("%s\n", word);
}
}
return 0;
}