【发布时间】:2010-07-30 14:36:52
【问题描述】:
这是如何工作的?
我知道使用它你传入:
- 开始:字符串(例如“第 1 项、第 2 项、第 3 项”)
- delim:分隔符字符串(例如“,”)
- tok: 对包含令牌的字符串的引用
- nextpos(可选):引用原始字符串中下一个标记开始的位置
- sdelim(可选):指向将包含标记起始分隔符的字符的指针
- edelim(可选):指向一个字符的指针,该字符将包含标记的结束分隔符
代码:
#include <stdlib.h>
#include <string.h>
int token(char* start, char* delim, char** tok, char** nextpos, char* sdelim, char* edelim) {
// Find beginning:
int len = 0;
char *scanner;
int dictionary[8];
int ptr;
for(ptr = 0; ptr < 8; ptr++) {
dictionary[ptr] = 0;
}
for(; *delim; delim++) {
dictionary[*delim / 32] |= 1 << *delim % 32;
}
if(sdelim) {
*sdelim = 0;
}
for(; *start; start++) {
if(!(dictionary[*start / 32] & 1 << *start % 32)) {
break;
}
if(sdelim) {
*sdelim = *start;
}
}
if(*start == 0) {
if(nextpos != NULL) {
*nextpos = start;
}
*tok = NULL;
return 0;
}
for(scanner = start; *scanner; scanner++) {
if(dictionary[*scanner / 32] & 1 << *scanner % 32) {
break;
}
len++;
}
if(edelim) {
*edelim = *scanner;
}
if(nextpos != NULL) {
*nextpos = scanner;
}
*tok = (char*)malloc(sizeof(char) * (len + 1));
if(*tok == NULL) {
return 0;
}
memcpy(*tok, start, len);
*(*tok + len) = 0;
return len + 1;
}
我得到了大部分,除了:
dictionary[*delim / 32] |= 1 << *delim % 32;
和
dictionary[*start / 32] & 1 << *start % 32
是魔法吗?
【问题讨论】:
-
我知道这两行代码可以找到分隔符,但它没有循环遍历分隔符字符串?