#define foreach_32(word, wordlist, next) \ for (next = &wordlist[strspn(wordlist, " ")], \ strncpy(word, next, sizeof(word)), \ word[strcspn(word, " ")] = '\0', \ word[sizeof(word) - 1] = '\0', \ next = strchr(next, ' '); \ strlen(word); \ next = next ? &next[strspn(next, " ")] : "", \ strncpy(word, next, sizeof(word)), \ word[strcspn(word, " ")] = '\0', \ word[sizeof(word) - 1] = '\0', \ next = strchr(next, ' '))
或者
#define foreach_token(word, wordlist, next, token) \ for (next = &wordlist[strspn(wordlist, token)], \ strncpy(word, next, sizeof(word)), \ word[strcspn(word, token)] = '\0', \ word[sizeof(word) - 1] = '\0', \ next = strchr(next, token[0]); \ strlen(word); \ next = next ? &next[strspn(next, token)] : "", \ strncpy(word, next, sizeof(word)), \ word[strcspn(word, token)] = '\0', \ word[sizeof(word) - 1] = '\0', \ next = strchr(next, token[0]))
使用:
char prefix[32], word[100], tmp[100], *next, *value; char* wordlist = "hello world how are you find thank you and how about you ?"; std::cout << "\n=========================" << std::endl; foreach_32(word, wordlist, next) { std::cout << word << std::endl; } std::cout << "\n=========================" << std::endl; wordlist = "hello world,how are you,find thank you,and how about you ?"; foreach_token(word,wordlist,next,",") { std::cout << word << std::endl; }