现在的位置: 首页 > 综合 > 正文

字符串分割

2018年05月08日 ⁄ 综合 ⁄ 共 1140字 ⁄ 字号 评论关闭
#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;
	}

抱歉!评论已关闭.